วัน: 1 ตุลาคม 2020

Tabulator: Customizing Data Table with Score ColumnTabulator: Customizing Data Table with Score Column

การสร้างตารางข้อมูลด้วย Tabulator สามารถทำได้ง่ายๆ โดยใช้ข้อมูลจากตาราง HTML ที่มีอยู่แล้ว บทความนี้จะสอนวิธีการเพิ่มคอลัมน์ ‘score’ แบบสุ่มเข้าไปในตาราง Tabulator ด้วยการใช้ JavaScript ร่วมกับ HTML. ดังนั้น, ถ้าคุณต้องการที่จะสร้างตารางข้อมูลที่มีความซับซ้อนและสามารถปรับแต่งได้ง่ายๆ ตามต้องการ, Tabulator คือเครื่องมือที่ดีที่สุดสำหรับคุณ.

การสร้างตาราง HTML ด้วยข้อมูลพื้นฐาน

ตัวอย่างโค้ด HTML ด้านล่างนี้จะแสดงวิธีการสร้างตาราง HTML ที่มีข้อมูลพื้นฐาน:

XML

<table id="source-table">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Surname</th>
            <th>Age</th>
            <th>Gender</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>Pitt</td>
            <td>Phunsanit</td>
            <td>43</td>
            <td>Male</td>
        </tr>
        <tr>
            <td>2</td>
            <td>พิชญ์</td>
            <td>พันธุ์สนิท</td>
            <td>43</td>
            <td>ชาย</td>
        </tr>
    </tbody>
</table>

การเพิ่มคอลัมน์ ‘score’ แบบสุ่ม

เพื่อเพิ่มคอลัมน์ ‘score’ แบบสุ่ม, คุณสามารถใช้ JavaScript ในการสร้างตาราง Tabulator ดังนี้:

JavaScript

<script>
    function getTableDataFromHTML(tableId) {
        var table = document.getElementById(tableId);
        var rows = table.querySelectorAll('tbody tr');
        var data = [];
        rows.forEach(function (row) {
            var cells = row.querySelectorAll('td');
            data.push({
                id: cells[0].innerText,
                name: cells[1].innerText,
                surname: cells[2].innerText,
                age: cells[3].innerText,
                gender: cells[4].innerText,
                score: Math.floor(Math.random() * 100) + 1
            });
        });
        return data;
    }

    var tableData = getTableDataFromHTML('source-table');
    var table = new Tabulator('#tabulator-table', {
        data: tableData,
        columns: [
            {title: 'ID', field: 'id'},
            {title: 'Name', field: 'name'},
            {title: 'Surname', field: 'surname'},
            {title: 'Age', field: 'age'},
            {title: 'Gender', field: 'gender'},
            {title: 'Score', field: 'score'}
        ]
    });
</script>

บทสรุป

บทความนี้สอนวิธีการสร้างตารางข้อมูลด้วย Tabulator และเพิ่มคอลัมน์ ‘score’ แบบสุ่มเข้าไปในตาราง. ด้วยการใช้ JavaScript ร่วมกับ HTML, คุณสามารถสร้างตารางข้อมูลที่มีความซับซ้อนและสามารถปรับแต่งได้ง่ายๆ ตามต้องการ. หวังว่าบทความนี้จะช่วยให้คุณเข้าใจเกี่ยวกับการใช้งาน Tabulator และสร้างตารางข้อมูลที่มีความซับซ้อนได้ง่ายๆ.