使用数据表,我想只搜索第一个字母

Using data table I want to search with only first letter

本文关键字:搜索 第一个 数据表      更新时间:2023-09-26

我有一个包含所有者名称的表。用户希望能够从病房的第一个字母开始对表格进行排序。

示例:

1) Saurabh Gujarani2) Testsa

通过搜索"Sa"应该只列出-Saurabh Gujarani

但在我当前的代码中,它同时显示两者。

<script type="text/javascript">
$(document).ready(function () {
    $('#custom_2').dataTable({
       "aoColumnDefs": [
  { "bSearchable": false, "aTargets": [ 0,1,4,5,6,7,8 ] }
] } );
});
</script>

您可以如下修改DataTable的默认搜索功能。

//Declare table
var table = $('Table Selector').DataTable();
//on search box keyup
$('input[type = search]').on( 'keyup', function () {
    //start check from first character
   table.search( '^' + this.value, true, false).draw();
}); 

请查看工作演示https://jsfiddle.net/Prakash_Thete/b577yxa3/1/

我使用它让用户能够搜索元素周期表中的元素。

var searchString = document.getElementById("search").value; //The user input field
    if (searchString !== "") {
    var cols = document.querySelectorAll('#yourTableID td'), colslen = cols.length, i = -1;
	while(++i < colslen){
        if(cols[i].id.indexOf(searchString)>-1){
            //Do something to the tds that match the searchstring (acces with "cols[i]")
        } else {
           //Hide the tds that does not match the searchstring (eg. cols[i].style.display = "none";)

我将搜索字符串与<td>的id进行匹配,但如果您想搜索td.中的文本,我认为您可以将if语句中的.id替换为innerHTML或value

希望这能有所帮助!