Tag Archive Add

Byphunsanit

DataTables: Add row form JavaScript

ตัว DataTables โดยปกติจะดึงข้อมูลโดยใช้ AJAX, DOM ( html table ), JSON Array / object และยังสามารถใช้ API rows.add() ได้อีกวิธี

<!DOCTYPE html>
<html lang="en">

<head>
   <link crossorigin="anonymous" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css"
      integrity="sha512-jnSuA4Ss2PkkikSOLtYs8BlYIeeIK1h99ty4YfvRPAlzr377vr3CXDb7sb7eEEBYjDtcYj+AjBH3FLv5uSJuXg=="
      referrerpolicy="no-referrer" rel="stylesheet" />
   <link crossorigin="anonymous"
      href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/dataTables.bootstrap.min.css"
      integrity="sha512-BMbq2It2D3J17/C7aRklzOODG1IQ3+MHw3ifzBHMBwGO/0yUqYmsStgBjI0z5EYlaDEFnvYV7gNYdD3vFLRKsA=="
      referrerpolicy="no-referrer" rel="stylesheet" />
   <link crossorigin="anonymous" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css"
      integrity="sha512-Kc323vGBEqzTmouAECnVceyQqyqdsSiqLQISBL29aUW4U/M7pSPA/gEUZQqv1cwx4OnYxTxve5UMg5GT6L4JJg=="
      referrerpolicy="no-referrer" rel="stylesheet" />

   <link rel="stylesheet" href="styles.css">
   <meta charset="utf-8">
   <meta name="author" content="Pitt Phunsanit">
   <title>DataTables: Add row form JavaScript</title>
   <style id="figma-style"></style>
</head>

<body>
   <table class="table table-hover table-striped" id="tableA"></table>
   <label for="jsonTA">JSON Data</label>
   <textarea class="form-control" id="jsonTA" rows="10"></textarea>

   <script crossorigin="anonymous"
      integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g=="
      referrerpolicy="no-referrer" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

   <script crossorigin="anonymous"
      integrity="sha512-TPh2Oxlg1zp+kz3nFA0C5vVC6leG/6mm1z9+mA81MI5eaUVqasPLO8Cuk4gMF4gUfP5etR73rgU/8PNMsSesoQ=="
      referrerpolicy="no-referrer"
      src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.11.8/umd/popper.min.js"></script>

   <script crossorigin="anonymous"
      integrity="sha512-ykZ1QQr0Jy/4ZkvKuqWn4iF3lqPZyij9iRv6sGqLRdTPkY69YX6+7wvVGmsdBbiIfN/8OdsI7HABjvEok6ZopQ=="
      referrerpolicy="no-referrer"
      src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/js/bootstrap.min.js"></script>

   <script crossorigin="anonymous"
      integrity="sha512-BkpSL20WETFylMrcirBahHfSnY++H2O1W+UnEEO4yNIl+jI2+zowyoGJpbtk6bx97fBXf++WJHSSK2MV4ghPcg=="
      referrerpolicy="no-referrer"
      src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"></script>

   <script src="https://cdn.datatables.net/plug-ins/2.1.7/sorting/custom-data-source/dom-checkbox.js"></script>

   <script>
      $(document).ready(function () {

         let polyglots = {
            "languages": {
               "en": {
                  "checked": true,
                  "items": 0,
                  "name": "English"
               },
               "zh": {
                  "checked": true,
                  "items": 0,
                  "name": "Chinese (mandarin): 你好,世界"
               },
               "hi": {
                  "checked": true,
                  "items": 0,
                  "name": "Hindi: वेबसाइट"
               },
               "es": {
                  "checked": true,
                  "items": 0,
                  "name": "Spanish"
               },
               "fr": {
                  "checked": true,
                  "items": 0,
                  "name": "French"
               },
               "ar": {
                  "checked": true,
                  "items": 0,
                  "name": "Arabic: वेबसाइट"
               },
               "bn": {
                  "checked": true,
                  "items": 0,
                  "name": "Bengali (Bangla): এই টি একটি বাংলা বাক্য।"
               },
               "ru": {
                  "checked": true,
                  "items": 0,
                  "name": "Russian"
               },
               "id": {
                  "checked": true,
                  "items": 0,
                  "name": "Indonesian"
               },
               "de": {
                  "checked": true,
                  "items": 0,
                  "name": "German"
               },
               "th": {
                  "checked": true,
                  "items": 0,
                  "name": "Thai: ภาษาไทย"
               },
               "ab": {
                  "checked": false,
                  "items": 0,
                  "name": "Abkhazian"
               },
               "aa": {
                  "checked": false,
                  "items": 0,
                  "name": "Afar"
               },
               "af": {
                  "checked": false,
                  "items": 0,
                  "name": "Afrikaans"
               },
               "ak": {
                  "checked": false,
                  "items": 0,
                  "name": "Akan"
               },
               "sq": {
                  "checked": false,
                  "items": 0,
                  "name": "Albanian"
               },
               "am": {
                  "checked": false,
                  "items": 0,
                  "name": "Amharic"
               },
               "an": {
                  "checked": false,
                  "items": 0,
                  "name": "Aragonese"
               },
               "hy": {
                  "checked": false,
                  "items": 0,
                  "name": "Armenian"
               },
               "as": {
                  "checked": false,
                  "items": 0,
                  "name": "Assamese"
               }
            }
         };
         let tableA = $('#tableA');
         let tables = [];

         // languages table
         let options = {
            "autoWidth": false,
            "columns": [
               {
                  "orderable": false,
                  "render": function (data, type, row, meta) {
                     return meta.row + 1;
                  },
                  "title": "No.",
                  "width": "10px"
               },
               {
                  "orderable": true,
                  "render": function (data, type, row, meta) {
                     return '<input' + (row.checked ? ' checked' : '') + ' type="checkbox" value="' + row.lang + '">';
                  },
                  "searchable": false,
                  "title": "Enable",
                  "type": "dom-checkbox",
                  "width": "10px"
               }, {
                  "data": "name",
                  "orderable": true,
                  "title": "Language"
               }
               , {
                  "data": "lang",
                  "orderable": true,
                  "title": "ISO Code",
                  "width": "90px"
               },
               {
                  "orderable": true,
                  "render": function (data, type, row, meta) {
                     return '<div title="Count ' + row.lang + '">' + row.items + '</div>';
                  },
                  "title": "Items",
                  "width": "10px"
               },
               {
                  "orderable": false,
                  "render": function (data, type, row, meta) {
                     if (row.lang == 'en') {
                        return '';
                     } else {
                        return '<div class="btn fas fa-edit" id="lang' + row.lang + 'Edit" title="Edit ' + row.lang + '">&nbsp;</div>';
                     }
                  },
                  "title": "",
                  "width": "10px"
               }
            ],
            "createdRow": function (row, data, dataIndex) {
               if (data.checked) {
                  $(row).addClass('table-info');
               }
            }
         };
         tables['languages'] = tableA.DataTable(options);

         //add data to DataTable
         let data = [];

         for (let lang in polyglots.languages) {
            data.push({
               "checked": polyglots.languages[lang].checked,
               "items": polyglots.languages[lang].items,
               "lang": lang,
               "name": polyglots.languages[lang].name
            });
         }
         tables['languages'].clear().rows.add(data).draw();

         //preview data
         $('#jsonTA').val(JSON.stringify(data));

      });
   </script>
</body>

</html>

จากตัวอย่าง

  • บรรทัด 28 โหลด libraries มาจาก CDN
  • บรรทัด 52 เป็น JSON ที่เก็บข้อมูลเอาไว้แต่รูปแบบไม่ตรงกับ data ของ DataTable
  • บรรทัด 220 เป็นโค้ทที่เปลี่ยนรูปแบบข้อมูลใหม่
  • บรรทัด 231 update DataTable ใหม่โดยคำสั่ง.clear().rows.add(data).draw();

อ่านเพิ่มเติม