กำหนดจำนวนตัวอักษรในช่องค้นหาของ datatables
2022-04-05 Games 3562022-04-06 Games
1. กำหนด Maxlength
$(document).ready( function () { $(document).on("preInit.dt", function(){ $(".dataTables_filter input[type='search']").attr("maxlength", 3); }); var table = $('#example').DataTable(); } );
ที่มา datatables.net
2. กำหนด Minlength สำหรับการค้นหา
เพิ่มในส่วนของ initComplete ดังนี้
"initComplete": () => { var $searchInput = $('div.dataTables_filter input'); $searchInput.unbind(); $searchInput.bind('input', function(e) { if(this.value.length == 3 || this.value.length == 0) { table.search( this.value ).draw(); } }); }
ที่มา stackoverflow.com
ตัวอย่าง code ทั้งหมด
$(document).ready(function() { $(document).on("preInit.dt", function(){ $(".dataTables_filter input[type='search']").attr("maxlength", 3); }); var jsonData = "layout/tabien/js/tabien.json"; var table = $('#tabien-table').DataTable({ "ajax": jsonData, "columns" : [ { "data" : 0 }, { "data" : null, "render": function(data){ html = ""+data[1]+""; return html; } }, { "data" : null, "render": function(data){ html = ""+data[2]+""; if(data[2]=="ขายแล้ว"){html = ""+data[2]+"";} if(data[2]=="ปิด"){html = ""+data[2]+"";} if(data[2]=="มาใหม่"){html = ""+data[2]+"";} return html; } }, { "data" : 3 }, { "data" : 4 }, { "data" : 5 }, { "data" : 6 }, { "data" : 7 }, ], "columnDefs": [ { "targets": [ 8 ], "data": 0, "render": function(data){ html = "" return html; } }, { responsivePriority: 1, targets: 1 }, { responsivePriority: 2, targets: 8 } ], "responsive" : true, "autoWidth" : false, "initComplete": () => { $("#tabien-table").show(); let loading = document.getElementById("show-loading"); loading.style.display = "none"; var $searchInput = $('div.dataTables_filter input'); $searchInput.unbind(); $searchInput.bind('input', function(e) { if(this.value.length == 3 || this.value.length == 0) { table.search( this.value ).draw();
} }); } }); });
datatables | Java Script