2

I am using jQuery DataTables Individual Column Searching, on one of my tables and one of my columns contains checkboxes.

HTML

<table id="NewTable" class="table table-bordered table-striped">
    <thead>
        <tr>
            <th class="col-sm-1 text-center ">
                @Html.DisplayNameFor(model => model.c_AMake.AMake)
            </th>
            <th class="text-center col-sm-1">
                @Html.DisplayNameFor(model => model.Model)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Test)
            </th>
        </tr>
    </thead>
    <tfoot id="NewTable-Foot" style="display: table-header-group">
        <tr>
            <th class="col-sm-1 text-center ">
                @Html.DisplayNameFor(model => model.c_AMake.AMake)
            </th>
            <th class="text-center col-sm-1">
                @Html.DisplayNameFor(model => model.Model)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Test)
            </th>
        </tr>
    </tfoot>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.c_AMake.AMake)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Model)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Test)
            </td>
        </tr>
    }
</table>

jQuery

var newTable = $('#NewTable tfoot th').length;

// Setup - add a text input to each footer cell
$("#NewTable tfoot th").each(function (index) {
    if (index !== newTable - 1) {
        var title = $(this).text().trim();
        $(this).html('<input type="text" class="form-control" placeholder="' + title + '"/>');
    }
});

var newDTTable = $('#NewTable').DataTable();

newDTTable.columns().every(function () {
    var that = this;
    console.log(this.data());
    $('input', this.footer()).on('keyup change',
        function () {
            if (that.search() !== this.value) {
                that
                    .search(this.value)
                    .draw();
            }
        });
});

This displays the column I am speaking of like so:

enter image description here

But if I start typing "True" into the textbox.. my table refreshes to say "No matching records found". Fair enough, because the checkbox doesn't have a value of "true" in terms of HTML rendering.. instead it just says `checked="checked".

But as an argument, when I do console.log(this.data()), I see every row in the table and those values are coming back as "True", "False", "False".

enter image description here

Is there a way to search for checkboxes that are either checked or unchecked via jQuery datatables?

UPDATE

Here is how I am creating the search boxes:

$("#NewTable tfoot th").each(function (index) {
    if (index !== newTable - 1) {
        var title = $(this).text().trim();
        $(this).html('<input type="text" class="form-control" placeholder="' + title + '"/>');
    }
});

UPDATE 2

var newDTTable = $('#NewTable').DataTable({
    dom: 'Bfrtip',
    buttons: [
    {
        extend: 'excel',
        exportOptions: {
            columns: ':not(:last-child)'
        }
    }],
    aoColumnDefs: [
        {
            "render": function (data, type, row) {
                if (data.indexOf("checked") > -1) {
                    return data + "<input type='hidden' value='True' />";
                }
                else return data + "<input type='hidden' value='False' />";
            },
            "targets": 5
        },
        { "bSortable": false, "aTargets": [2, 18] },
        { "bSearchable": false, "aTargets": [4,7,8,9,10,11,12,13,14,15,16,17,18] }
    ]
});

newDTTable.columns().every(function (colIdx) {
    var that = this;
    console.log(this.data());
    $('input', this.footer()).on('keyup change',
        function() {
            if (that.search() !== this.value) {
                that
                    .search(this.value)
                    .draw();
            }
        });
});

Here is my definition/creation of my datatable.. there are a few hidden columns which don't matter in the context of this question.

7
  • Downvote with no comment as to why? Commented Aug 14, 2017 at 12:59
  • Probably someone did not bother to read? Seems interesting question. I'll give it try. Commented Aug 14, 2017 at 13:02
  • Do you actually want to search for the entries via textfield? wouldnt it make more sense to make a checkbox for filtering aswell? Commented Aug 14, 2017 at 13:43
  • It does make more sense, but I haven't seen any demos on how that can be done. Commented Aug 14, 2017 at 13:44
  • give me a minute Commented Aug 14, 2017 at 13:44

5 Answers 5

3
+100

I created (actually cannibalized ;)) a fiddle here: http://jsfiddle.net/gk67srwb/2/

The basic trick is to append a hidden input field to your checkbox when rendering your checkbox columns:

var table = $('#example').DataTable({
    "columnDefs": [
        {
            "render": function ( data, type, row ) {
            console.log(data);
            if(data === "True"){
                return "<input type='checkbox' checked disabled /><input type='hidden' value='" + data + "' />";
                }
                else return "<input type='checkbox' disabled /><input type='hidden' value='" + data + "' />";
            },
            "targets": 2
        }
        ]
});

When you now enter true // false into the column search box, the rows are filtered accordingly. Of course you could give the hidden field a more convenient value (0 / 1) or create a dropdown/checkbox.

Hope this helps you!

Sign up to request clarification or add additional context in comments.

11 Comments

what is targets?
targets is the 0-based index of your columns. So for my example table, the ID column is 0, DESCRIPTION is 1 and CHECK is 2. You can also pass an array here (e.g. "targets": [2, 3, 4, 7]) if you have multiple checkbox columns. Link to the official documentation: datatables.net/reference/option/columnDefs.targets
This does not work for me, because in your jsfiddle.. you are giving the td elements a value of either true or false.. whereas in mine.. the td elements will have a value of <td> <input disabled="disabled" class="check-box" type="checkbox" checked="checked"> </td>.. so your data attribute will literally get values of either True or False
I have updated fiddle, just added condition which you need, you can change condition based on your case jsfiddle.net/gk67srwb/5
Could you update your code with the lines where you actually create your DataTables object? The html output which you posted is created by DataTables and you can modify this.
|
1

Updated in 2020 using Angular 9

<td><div style="display:none">{{pi.coverageIssue}}</div><input type="checkbox" class="claimsList-checkbox" disabled [checked]=pi.coverageIssue></td>

And my search in TypeScript was very simple

applyFilter(column,value) {
    var dTable = $('#claimSearchTable').DataTable();
    dTable.column(column).search(value).draw();     
}

Comments

0

Maybe this?

var newTable = $('#NewTable tfoot th').length;

// Setup - add a text input to each footer cell
$("#NewTable tfoot th").each(function (index) {
    if (index !== newTable - 1) {
        var title = $(this).text().trim();
        if(title=='Test'){
            var html = '<select class="form-control">';
            html += "<option value='' selected>Any</option>"
            html += "<option value='checked' selected>True</option>"
            html += "<option value='box"+'"'+">' selected>False</option>"
            html += "</select>"
            $(this).html(html)
        }else
            $(this).html('<input type="text" class="form-control" placeholder="' + title + '"/>');
    }
});
var newDTTable = $('#NewTable').DataTable();

newDTTable.columns().every(function () {
    var that = this;
    console.log(this.data());
    $('input, select', this.footer()).on('keyup change',
        function () {
            if (that.search() !== this.value) {
                that
                    .search(this.value)
                    .draw();
            }
        });
});

Comments

0

You may see in this example that in Datatables you need to define the type of a table cell if it is different from a normal text.

Anyway, you may always apply a custom filter.

Let's assume you have the select element in the first column. You need:

  • a global variable or something similar to save the index of the current search box
  • save this value on input instead of keyup change events. This in order to call the custom search only one time.
  • in the custom search function you need to test if you are acting on the first column and so apply the custom search.

I used the example table and not your table. This should not be a problem. This is only a way to describe how to solve your issue.

The snippet:

var newTable = $('#NewTable tfoot th').length;
//
// added new variable
//
var selectedIdx;

// Setup - add a text input to each footer cell
$("#NewTable tfoot th").each(function (index) {
    if (index !== newTable - 1) {
        var title = $(this).text().trim();
        $(this).html('<input type="text" class="form-control" placeholder="' + title + '"/>');
    }
});

var newDTTable = $('#NewTable').DataTable();

newDTTable.columns().every(function () {
    var that = this;
    //
    // changed the events from keyup change to input
    //
    $('input', this.footer()).on('input', function (e) {
        //
        // save current search input index...
        //
        selectedIdx = that.footer().cellIndex;
        //
        // call the custom filter....
        //
        newDTTable.draw(false);
    });
});
$.fn.dataTableExt.afnFiltering.push(
        //
        // custom filter .....
        //
        function (oSettings, aData, iDataIndex) {
            var column = newDTTable.column(selectedIdx);
            var footer_txt = $('input', column.footer()).val();
            var cell_data = aData[selectedIdx];
            //
            // if filtering on the select option column get current value of the select box
            //
            if (selectedIdx == 0) {
                cell_data = $(oSettings.aoData[iDataIndex]
                        .anCells[selectedIdx]).find(':checked').is(":checked");
                if (footer_txt.toUpperCase().charAt(0) == 'T') {
                    footer_txt = true;
                } else {
                    if (footer_txt.toUpperCase().charAt(0) == 'F') {
                        footer_txt = false;
                    } else {
                        footer_txt = undefined;
                    }
                }
                //
                // searching on checkbox.......
                //
                return (footer_txt == undefined) ? true : footer_txt == cell_data;
            }

            //
            // search....
            //
            return cell_data.search(footer_txt) >= 0;
        }
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>


<table id="NewTable" class="display" cellspacing="0" width="100%">
    <thead>
    <tr>
        <th>test</th>
        <th>Name</th>
        <th>Position</th>
        <th>Office</th>
        <th>Age</th>
        <th>Start date</th>
        <th>Salary</th>
    </tr>
    </thead>
    <tfoot>
    <tr>
        <th>test</th>
        <th>Name</th>
        <th>Position</th>
        <th>Office</th>
        <th>Age</th>
        <th>Start date</th>
        <th>Salary</th>
    </tr>
    </tfoot>
    <tbody>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Tiger Nixon</td>
        <td>System Architect</td>
        <td>Edinburgh</td>
        <td>61</td>
        <td>2011/04/25</td>
        <td>$320,800</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox"></td>
        <td>Garrett Winters</td>
        <td>Accountant</td>
        <td>Tokyo</td>
        <td>63</td>
        <td>2011/07/25</td>
        <td>$170,750</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox"></td>
        <td>Ashton Cox</td>
        <td>Junior Technical Author</td>
        <td>San Francisco</td>
        <td>66</td>
        <td>2009/01/12</td>
        <td>$86,000</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Cedric Kelly</td>
        <td>Senior Javascript Developer</td>
        <td>Edinburgh</td>
        <td>22</td>
        <td>2012/03/29</td>
        <td>$433,060</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Airi Satou</td>
        <td>Accountant</td>
        <td>Tokyo</td>
        <td>33</td>
        <td>2008/11/28</td>
        <td>$162,700</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Brielle Williamson</td>
        <td>Integration Specialist</td>
        <td>New York</td>
        <td>61</td>
        <td>2012/12/02</td>
        <td>$372,000</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Herrod Chandler</td>
        <td>Sales Assistant</td>
        <td>San Francisco</td>
        <td>59</td>
        <td>2012/08/06</td>
        <td>$137,500</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Rhona Davidson</td>
        <td>Integration Specialist</td>
        <td>Tokyo</td>
        <td>55</td>
        <td>2010/10/14</td>
        <td>$327,900</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Colleen Hurst</td>
        <td>Javascript Developer</td>
        <td>San Francisco</td>
        <td>39</td>
        <td>2009/09/15</td>
        <td>$205,500</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Sonya Frost</td>
        <td>Software Engineer</td>
        <td>Edinburgh</td>
        <td>23</td>
        <td>2008/12/13</td>
        <td>$103,600</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Jena Gaines</td>
        <td>Office Manager</td>
        <td>London</td>
        <td>30</td>
        <td>2008/12/19</td>
        <td>$90,560</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Quinn Flynn</td>
        <td>Support Lead</td>
        <td>Edinburgh</td>
        <td>22</td>
        <td>2013/03/03</td>
        <td>$342,000</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Charde Marshall</td>
        <td>Regional Director</td>
        <td>San Francisco</td>
        <td>36</td>
        <td>2008/10/16</td>
        <td>$470,600</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Haley Kennedy</td>
        <td>Senior Marketing Designer</td>
        <td>London</td>
        <td>43</td>
        <td>2012/12/18</td>
        <td>$313,500</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Tatyana Fitzpatrick</td>
        <td>Regional Director</td>
        <td>London</td>
        <td>19</td>
        <td>2010/03/17</td>
        <td>$385,750</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Michael Silva</td>
        <td>Marketing Designer</td>
        <td>London</td>
        <td>66</td>
        <td>2012/11/27</td>
        <td>$198,500</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Paul Byrd</td>
        <td>Chief Financial Officer (CFO)</td>
        <td>New York</td>
        <td>64</td>
        <td>2010/06/09</td>
        <td>$725,000</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Gavin Cortez</td>
        <td>Team Leader</td>
        <td>San Francisco</td>
        <td>22</td>
        <td>2008/10/26</td>
        <td>$235,500</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Zorita Serrano</td>
        <td>Software Engineer</td>
        <td>San Francisco</td>
        <td>56</td>
        <td>2012/06/01</td>
        <td>$115,000</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Jennifer Acosta</td>
        <td>Junior Javascript Developer</td>
        <td>Edinburgh</td>
        <td>43</td>
        <td>2013/02/01</td>
        <td>$75,650</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Cara Stevens</td>
        <td>Sales Assistant</td>
        <td>New York</td>
        <td>46</td>
        <td>2011/12/06</td>
        <td>$145,600</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Hermione Butler</td>
        <td>Regional Director</td>
        <td>London</td>
        <td>47</td>
        <td>2011/03/21</td>
        <td>$356,250</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Lael Greer</td>
        <td>Systems Administrator</td>
        <td>London</td>
        <td>21</td>
        <td>2009/02/27</td>
        <td>$103,500</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Jonas Alexander</td>
        <td>Developer</td>
        <td>San Francisco</td>
        <td>30</td>
        <td>2010/07/14</td>
        <td>$86,500</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Shad Decker</td>
        <td>Regional Director</td>
        <td>Edinburgh</td>
        <td>51</td>
        <td>2008/11/13</td>
        <td>$183,000</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Michael Bruce</td>
        <td>Javascript Developer</td>
        <td>Singapore</td>
        <td>29</td>
        <td>2011/06/27</td>
        <td>$183,000</td>
    </tr>
    <tr>
        <td><input disabled="disabled" class="check-box" type="checkbox" checked="checked"></td>
        <td>Donna Snider</td>
        <td>Customer Support</td>
        <td>New York</td>
        <td>27</td>
        <td>2011/01/25</td>
        <td>$112,000</td>
    </tr>
    </tbody>
</table>

Comments

0

Despite previous postings I couldn't get it to work. Datatables (v1.10.15) just did not pick up the hidden values in the checkboxes when typing True or False in the column search box. So for those of who you need an alternative solution, the following fixed it for me.

Replace the razor code

@Html.DisplayFor(modelItem => item.Test)

with this for simple True and False values

@Html.ValueFor(modelItem => item.Test)

And next change the columndefs to:

"columnDefs": [
{
    "targets": 3,
    "render": function (data, type, row, meta) {

        if (type === 'display') {
            if (data === "True") {
                return "<input disabled='disabled' class='check-box' type='checkbox' checked='checked'>";
            }
            else return "<input disabled='disabled' class='check-box' type='checkbox'>";
        }

        return data;
    }
}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.