sondmk header
เรียนรู้การเขียน JavaScript เบื้องต้น

Javascript : Confirm And Call Function()

Post by Goborijung at 2021-06-08 14:27:13 | ID: 1234

<button type="button" name="btnExport" onclick="return confirm('Export to CRV ?')?myFunction():'';"><i class="fa fa-file-excel"></i> Export</button>

<script>
function myFunction()
{
	alert('ok');
}
</script>

Javascript : Export Table Data to CSV (Excel)

Post by Goborijung at 2021-06-07 22:32:06 | ID: 1231

ref : https://jsfiddle.net/gengns/j1jm2tjx/

<button onclick="exportTableToCSV('members.csv')">Export HTML Table To CSV File</button>
<table border='1'>
    <tr>
        <th>Name</th>
        <th>Email</th>
        <th>Country</th>
    </tr>
    <tr>
        <td>John Doe</td>
        <td>john@gmail.com</td>
        <td>USA</td>
    </tr>
    <tr>
        <td>Stephen Thomas</td>
        <td>stephen@gmail.com</td>
        <td>UK</td>
    </tr>
    <tr>
        <td>Natly Oath</td>
        <td>natly@gmail.com</td>
        <td>France</td>
    </tr>
</table>

<script>
function downloadCSV(csv, filename) {
    var csvFile;
    var downloadLink;

    // CSV file
    //csvFile = new Blob([csv], {type: "text/csv"});
    csvFile = new Blob(["/uFEFF"+csv], {type: "text/csv; charset=utf-18"}); //เปลี่ยน /uFEFF ให้เป็น BlackSlash สำหรับข้อความภาษาไทย

    // Download link
    downloadLink = document.createElement("a");

    // File name
    downloadLink.download = filename;

    // Create a link to the file
    downloadLink.href = window.URL.createObjectURL(csvFile);

    // Hide download link
    downloadLink.style.display = "none";

    // Add the link to DOM
    document.body.appendChild(downloadLink);

    // Click download link
    downloadLink.click();
}

function exportTableToCSV(filename) {
    var csv = [];
    var rows = document.querySelectorAll("table tr");
    var rowStart = 0;
    var colStart = 0;
    for (var i = rowStart; i < rows.length; i++) {
        var row = [], cols = rows[i].querySelectorAll("td, th"); //เอาหัวคอลัมด้วย
        //var row = [], cols = rows[i].querySelectorAll("td"); //เอาแค่ใส้ ไม่เอาหัวคอลัม
        
        for (var j = colStart; j < cols.length; j++) 
            row.push(cols[j].innerText);
        
        csv.push(row.join(","));        
    }

    // Download CSV file
    downloadCSV(csv.join("/n"), filename); //เปลี่ยน /n ให้เป็น BlackSlash 
}
</script>

Javascript : Export Table Data to CSV (Excel) V2

Post by Goborijung at 2021-06-09 00:18:16 | ID: 1240

<body>
    <div style="padding: 1rem">
        <button class="button" id="export">Export</button>
        <table id="exportMe" class="table" border=1>
            <thead>
                <tr>
                    <th data-type="number">No.</th>
                    <th>First name</th>
                    <th>Last name</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>1</td>
                    <td>Andrea</td>
                    <td>Ross</td>
                </tr>
                <tr>
                    <td>2</td>
                    <td>Penelope</td>
                    <td>Mills</td>
                </tr>
                <tr>
                    <td>3</td>
                    <td>Sarah</td>
                    <td>Grant</td>
                </tr>
                <tr>
                    <td>4</td>
                    <td>Vanessa</td>
                    <td>Roberts</td>
                </tr>
                <tr>
                    <td>5</td>
                    <td>Oliver</td>
                    <td>Alsop</td>
                </tr>
                <tr>
                    <td>6</td>
                    <td>Jennifer</td>
                    <td>Forsyth</td>
                </tr>
                <tr>
                    <td>7</td>
                    <td>Michelle</td>
                    <td>King</td>
                </tr>
                <tr>
                    <td>8</td>
                    <td>Steven</td>
                    <td>Kelly</td>
                </tr>
                <tr>
                    <td>9</td>
                    <td>Julian</td>
                    <td>Ferguson</td>
                </tr>
                <tr>
                    <td>10</td>
                    <td>Chloe</td>
                    <td>Ince</td>
                </tr>
            </tbody>
        </table>
    </div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const table = document.getElementById('exportMe');
    const exportBtn = document.getElementById('export');

    const toCsv = function(table) {
        // Query all rows
        const rows = table.querySelectorAll('tr');

        return [].slice.call(rows)
            .map(function(row) {
                // Query all cells
                const cells = row.querySelectorAll('th,td');
                return [].slice.call(cells)
                    .map(function(cell) {
                        return cell.textContent;
                    })
                    .join(',');
            })
            .join('/n'); //replace /n to BlackSlash
    };

    const download = function(text, fileName) {
        const link = document.createElement('a');
        link.setAttribute('href', `data:text/csv;charset=utf-8,${encodeURIComponent(text)}`);
        link.setAttribute('download', fileName);

        link.style.display = 'none';
        document.body.appendChild(link);

        link.click();

        document.body.removeChild(link);
    };

    exportBtn.addEventListener('click', function() {
        // Export to csv
        const csv = toCsv(table);

        // Download it
        download(csv, 'download.csv');
    });
});
</script>

Javascript : Get Cell Values

Post by Goborijung at 2020-01-23 14:16:31 | ID: 370

http://dotnetlearners.com/javascript/find-table-cell-value-on-cell-table-click-using-javascript

Javascript : Get Cells By rows

Post by Goborijung at 2018-12-24 16:04:56 | ID: 58

<script language="javascript">
var tbl = document.getElementById("tblName");
var numrows = tbl.rows.length;
if (tbl != null) {
  for (var i=0; i<numrows; i++) {
     tbl.rows[i].onclick = function () {
        document.getElementById('id1').value = this.cells[0].innerHTML;
        document.getElementById('id2').value = this.cells[1].innerHTML; 
     }
  }
}
</script>

Javascript : GET Cells Value

Post by Goborijung at 2018-12-24 14:45:57 | ID: 57

<script language="javascript">
var tbl = document.getElementById("tblName");
if (tbl != null) {
  for (var i=0; i<tbl.rows.length; i++) {
    for (var j=0; j<tbl.rows[i].cells.length; j++) {
      tbl.rows[i].cells[j].onclick = function () {
        getval(this);
      };
    }
  }
}

function getval(cel) {
  //alert(cel.innerHTML);
  document.getElementById('idName').value = cel.innerHTML;
}
</script>

Javascript : Replace String

Post by Goborijung at 2021-06-08 16:16:32 | ID: 1235

<script>
var str = "Hello Word";
str = str.replace("Word","555");
alert(str); //Hello 555
</script>

Javascript : Resizeable Split View v.2

Post by Goborijung at 2021-06-09 00:07:40 | ID: 1239

<style>
    .container {
        display: flex;

        /* Misc */
        border: 1px solid #cbd5e0;
        height: 32rem;
        width: 100%;
    }
    .resizer[data-direction="horizontal"] {
        background-color: #cbd5e0;
        cursor: ew-resize;
        height: 100%;
        width: 2px;
    }
    .resizer[data-direction="vertical"] {
        background-color: #cbd5e0;
        cursor: ns-resize;
        height: 2px;
        width: 100%;
    }
    .container__left {
        /* Initially, the left takes 1/4 width */
        width: 25%;

        /* Misc */
        align-items: center;
        display: flex;
        justify-content: center;
    }
    .container__right {
        /* Take the remaining width */
        flex: 1;

        /* Misc */
        align-items: center;
        display: flex;
        flex-direction: column;
        justify-content: center;
    }
    .container__top {
        /* Initial height */
        height: 12rem;

        /* Misc */
        align-items: center;
        display: flex;
        justify-content: center;
    }
    .container__bottom {
        /* Take the remaining height */
        flex: 1;

        /* Misc */
        align-items: center;
        display: flex;
        justify-content: center;
    }
    </style>
</head>
<body>
    <div class="container">
        <div class="container__left">Left</div>
        <div class="resizer" data-direction="horizontal"></div>
        <div class="container__right">
            <div class="container__top">Top</div>
            <div class="resizer" data-direction="vertical"></div>
            <div class="container__bottom">Bottom</div>
        </div>
    </div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const resizable = function(resizer) {
        const direction = resizer.getAttribute('data-direction') || 'horizontal';
        const prevSibling = resizer.previousElementSibling;
        const nextSibling = resizer.nextElementSibling;

        // The current position of mouse
        let x = 0;
        let y = 0;
        let prevSiblingHeight = 0;
        let prevSiblingWidth = 0;

        // Handle the mousedown event
        // that's triggered when user drags the resizer
        const mouseDownHandler = function(e) {
            // Get the current mouse position
            x = e.clientX;
            y = e.clientY;
            const rect = prevSibling.getBoundingClientRect();
            prevSiblingHeight = rect.height;
            prevSiblingWidth = rect.width;

            // Attach the listeners to `document`
            document.addEventListener('mousemove', mouseMoveHandler);
            document.addEventListener('mouseup', mouseUpHandler);
        };

        const mouseMoveHandler = function(e) {
            // How far the mouse has been moved
            const dx = e.clientX - x;
            const dy = e.clientY - y;

            switch (direction) {
                case 'vertical':
                    const h = (prevSiblingHeight + dy) * 100 / resizer.parentNode.getBoundingClientRect().height;
                    prevSibling.style.height = `${h}%`;
                    break;
                case 'horizontal':
                default:
                    const w = (prevSiblingWidth + dx) * 100 / resizer.parentNode.getBoundingClientRect().width;
                    prevSibling.style.width = `${w}%`;
                    break;
            }

            const cursor = direction === 'horizontal' ? 'col-resize' : 'row-resize';
            resizer.style.cursor = cursor;
            document.body.style.cursor = cursor;

            prevSibling.style.userSelect = 'none';
            prevSibling.style.pointerEvents = 'none';

            nextSibling.style.userSelect = 'none';
            nextSibling.style.pointerEvents = 'none';
        };

        const mouseUpHandler = function() {
            resizer.style.removeProperty('cursor');
            document.body.style.removeProperty('cursor');

            prevSibling.style.removeProperty('user-select');
            prevSibling.style.removeProperty('pointer-events');

            nextSibling.style.removeProperty('user-select');
            nextSibling.style.removeProperty('pointer-events');

            // Remove the handlers of `mousemove` and `mouseup`
            document.removeEventListener('mousemove', mouseMoveHandler);
            document.removeEventListener('mouseup', mouseUpHandler);
        };

        // Attach the handler
        resizer.addEventListener('mousedown', mouseDownHandler);
    };

    // Query all resizers
    document.querySelectorAll('.resizer').forEach(function(ele) {
        resizable(ele);
    });
});
</script>

Javascript : Resizeable Split View

Post by Goborijung at 2021-06-09 00:04:56 | ID: 1238

 <style>
    .container {
        display: flex;

        /* Misc */
        border: 1px solid #cbd5e0;
        height: 16rem;
        width: 100%;
    }
    .container__left {
        /* Initially, the left takes 3/4 width */
        width: 75%;

        /* Misc */
        align-items: center;
        display: flex;
        justify-content: center;
    }
    .resizer {
        background-color: #cbd5e0;
        cursor: ew-resize;
        height: 100%;
        width: 2px;
    }
    .container__right {
        /* Take the remaining width */
        flex: 1;

        /* Misc */
        align-items: center;
        display: flex;
        justify-content: center;
    }
</style>
    
<div class="container">
        <div class="container__left">Left</div>
        <div class="resizer" id="dragMe"></div>
        <div class="container__right">Right</div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Query the element
    const resizer = document.getElementById('dragMe');
    const leftSide = resizer.previousElementSibling;
    const rightSide = resizer.nextElementSibling;

    // The current position of mouse
    let x = 0;
    let y = 0;
    let leftWidth = 0;

    // Handle the mousedown event
    // that's triggered when user drags the resizer
    const mouseDownHandler = function(e) {
        // Get the current mouse position
        x = e.clientX;
        y = e.clientY;
        leftWidth = leftSide.getBoundingClientRect().width;

        // Attach the listeners to `document`
        document.addEventListener('mousemove', mouseMoveHandler);
        document.addEventListener('mouseup', mouseUpHandler);
    };

    const mouseMoveHandler = function(e) {
        // How far the mouse has been moved
        const dx = e.clientX - x;
        const dy = e.clientY - y;

        const newLeftWidth = (leftWidth + dx) * 100 / resizer.parentNode.getBoundingClientRect().width;
        leftSide.style.width = `${newLeftWidth}%`;

        resizer.style.cursor = 'col-resize';
        document.body.style.cursor = 'col-resize';

        leftSide.style.userSelect = 'none';
        leftSide.style.pointerEvents = 'none';

        rightSide.style.userSelect = 'none';
        rightSide.style.pointerEvents = 'none';
    };

    const mouseUpHandler = function() {
        resizer.style.removeProperty('cursor');
        document.body.style.removeProperty('cursor');

        leftSide.style.removeProperty('user-select');
        leftSide.style.removeProperty('pointer-events');

        rightSide.style.removeProperty('user-select');
        rightSide.style.removeProperty('pointer-events');

        // Remove the handlers of `mousemove` and `mouseup`
        document.removeEventListener('mousemove', mouseMoveHandler);
        document.removeEventListener('mouseup', mouseUpHandler);
    };

    // Attach the handler
    resizer.addEventListener('mousedown', mouseDownHandler);
});
</script>

Javascript : Select on Change , onChange

Post by Goborijung at 2022-06-04 16:09:39 | ID: 1586

>> HTML
<select id='sl1'>
    <option value="1">One</option>
    <option value="2">Two</option>
</select>

>> Javascript
<script>
$('select').on('change', function()
{
    var id = this.id;
    var val = this.value;
                      
    alert( id+'/'+val);
});
</script>

--------------------

ตัวอย่างการใช้งาน

Enter your name: <input type="text" id="fname"> <script> document.getElementById("fname").onchange = function() {myFunction()}; function myFunction() { var x = document.getElementById("fname"); x.value = x.value.toUpperCase(); } </script>

12345>>>

Framework

Library


เครื่องมือพัฒนาเว็บ



การออกแบบและพัฒนาเว็บไซต์


Download SourceCode



copyAllright © 2016 soundmk.com