数据表搜索点击的div

时间:2016-08-19 03:35:31

标签: javascript php jquery html datatables

我以这种方式获取类别。

<?php foreach($categories as $category):?>
    <div id="search"><a href=""><?php echo $category->category;?></a></div></a>
<?php endforeach;?>

e.g。这给了我类别

Mobile Phones
Laptops
Fashion
Books
..
..

我正在尝试搜索我使用数据表单击的类别。 如果我点击笔记本电脑的数据表搜索功能,搜索笔记本电脑&#39;在表中。  javascripts:

var table=$('#tableid').DataTable();
$(document).on('click','#search',function(e)
{
        e.preventDefault();
        var search = $('#search').text();
        table.search(search).draw();
});   

但是,无论我点击哪个类别,都只搜索第一个类别。例如如果我点击&#39; Fashion&#39;,&#39;手机&#39;正在搜索中。如果我将div id改为class,则所有类别一次都在搜索框中试图搜索。如果我点击任何类别&#39;移动电话桌面时尚书...&#39;在表格中搜索。

1 个答案:

答案 0 :(得分:1)

您可以使用fnFilter过滤数据表。您需要做的一件事是您必须将数据表searching属性设置为true。我已经创建了一个示例来在您单击相应的div时过滤数据表。有关参考,请查看此Fiddle

<强> HTML

<table id="dataTable" class="display" cellspacing="0" width="100%">
<thead>
    <tr>                
        <th>Id</th>
        <th>Name</th>
        <th>Category</th>
    </tr>
</thead>
<tbody>
</tbody>

<强> CSS

.search {
    border-radius: 2px;
    background: #73AD21;
    margin-bottom : 10px;
    width: 100px;
    height: 20px;
}

<强> JS

$(document).ready(function() {
 var table = null;

  function createDatatable() {
    table = $('#dataTable').dataTable({
        bFilter: false,
        bLengthChange: false,
        searching : true,
        "sDom": 'lfrtip',
        pagingType: 'full',
        "oLanguage": {
            "oPaginate": {
                "sFirst": "<b><<</b>",
                "sLast": "<b>>></b>",
                "sNext": "<b>></b>",
                "sPrevious": "<b><</b>"
            }
        }
    });
  }

  createDatatable();

 //creating a temp json. you will get this from server side after ajax call 
 var jsonString = '[{"Id": 1,"Name": "Sony Vaio","Category": "Laptops"},{"Id": 2,"Name": "Samsung Galaxy","Category": "Mobile Phones"},{"Id": 3,"Name": "Dell","Category": "Laptops"}]';

        var data = JSON.parse(jsonString);
        for(i=0; i<data.length;i++) {
                $('#dataTable').dataTable().fnAddData([
                data[i].Id,
            data[i].Name,
            data[i].Category
        ]);
        }

 $(document).on('click','.search',function(e)
{
        var search = $(this).text();
        table.fnFilter(search.trim());
});  

});