简体   繁体   中英

DataTables with (filter by) from json data

I am trying make my filter works with json data from the server, someone could help me to do this?

I need filter by places: All, EUA,China, Spain

I am using: jquery.dataTables.js from: https://datatables.net

html:

  <div class=" dashboard">
  <div class="col-md-8 no-padding">
     <div class="form-group col-md-4 no-padding">
      <select class="form-control" id="sel1" >
        <option value="Filter by">Filter by country </option>
         <option value="All">All</option>
         <option value="First name">China</option>
         <option value="Last name">EUA</option>
         <option value="Last name">Spain</option>
      </select>
    </div>
  </div>

<br>
<br>
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
        <tr>
            <th>First name</th>
            <th>Place</th>

        </tr>
    </thead>
</table>

jquery:

    $(document).ready(function() {
       var dt = $('#example').dataTable();
       dt.fnDestroy();
    } );

   $(document).ready(function () {
  var url = 'http://www.json-generator.com/api/json/get/crcCiZXZfm?indent=2';
  var table = $('#example').DataTable({
        ajax: url,
    columns: [
        { data: 'name' },
        { data: 'place' }
    ]
  });
});

jsfiddle: http://jsfiddle.net/ntcwust8/120/

http://jsfiddle.net/f7debwj2/

Added the following code to your document.ready():

$('#sel1').change(function() {

  if (this.value === "All") {
    table
      .columns(1)
      .search('')
      .draw();
  }  

  else {
    table
      .columns(1)
      .search(this.value)
      .draw();
     }

});

So basically you tell your SELECT element to wait for its value to be changed. In order to show ALL, the .search() parameter is set to an empty string, which will return ALL. Otherwise the dropdown will trigger a table search on column(1) with the selected VALUE (not text!) of your SELECT and redraw your table.

Note : I also changed the value properties of your SELECT, since they were wrong in the beginning.

DataTables Documentation on column().search() can be found HERE .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM