jQuery DataTables: Multiple checkbox filtering

最后都变了- 提交于 2020-07-17 08:43:37

问题


I'm using jQuery datatables just to display some data, but know, i want to filtering those with multiple checkboxes.
My table contains this header: Host, Type, Record, Description, Free
And these are my checkboxes outside of the datatable:
Type: MX A CNAME
Free: 0 1 So at the begining I want to show all of the data. If someone now checks the checkbox MX, it should only show data with type MX. If someone checks MX, CNAME and 0, it should only show data with these filters. You know what I mean?
I've a plugins which can do this, but the checkboxes are under the columns, my checkboxes are outside the datatable.

Any idea?


回答1:


You should use this function:

function filterme() {
  //build a regex filter string with an or(|) condition
  var types = $('input:checkbox[name="type"]:checked').map(function() {
    return '^' + this.value + '\$';
  }).get().join('|');
  //filter in column 0, with an regex, no smart filtering, no inputbox,not case sensitive
  otable.fnFilter(types, 0, true, false, false, false);

  //build a filter string with an or(|) condition
  var frees = $('input:checkbox[name="free"]:checked').map(function() {
    return this.value;
  }).get().join('|');
  //now filter in column 2, with no regex, no smart filtering, no inputbox,not case sensitive
  otable.fnFilter(frees, 2, false, false, false, false);
}

Look at the comments to see what it does.

Call it from your html like this:

  <input onchange="filterme()" type="checkbox" name="free" value="0">0
  <input onchange="filterme()" type="checkbox" name="free" value="1">1

Plunker is a testbed for HTML and JS Snippets that greatly helps others to understand where your issue is located and to give a fast response on how to fix things. It simply works like html/js/css editor that renders your example on every keypress and is awesome.

Click here to see how I fixed your issue with Plunker

On the left side of the Plunker you will find the files I used in the process (index.html and script.js)

While this works and should give you an idea on how to continue, you should think about using radio buttons for the FREE filter, because it would make more sense.

Since this is a quiet complicated issue come back to me if something needs more explanation.



来源:https://stackoverflow.com/questions/22982180/jquery-datatables-multiple-checkbox-filtering

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!