Filter by checkbox

Filter by checkbox

Hildeb67Hildeb67 Posts: 64Questions: 18Answers: 1

Hello everyone, I have a DataTable with checkbox and now I want to filter whether checkbox is set or not. Text fields work. Does anyone here have an idea for me? Thanks and greetings Chris

here is a code excerpt

            { data: "EINZUGSERMAECHTIGUNG",
                render: function ( data, type, row ) {
                    if ( type === 'display' ) {
                        return '<input type="checkbox" class="editor-active">';
                    } else if (type === 'myExport') {
                        data=data.toString();
                        return data === '1' ? "X" : " ";
                    }
                    return data;
                },
                className: "checkboxanwesenheiten"  
            },  
            { data: "BANKNAME"},    

This question has accepted answers - jump to:

Answers

  • allanallan Posts: 63,488Questions: 1Answers: 10,468 Site admin

    It isn't particularly trivial unfortunately, but it can be done by passing a search function into column().search(). That fuction (per the docs) is given the column and row index each time it is called, so you could query the table to get the DOM node for the cell (cell().node()) and then get the checkbox from that, and check its state, and if it matches the search term or not.

    Allan

  • kthorngrenkthorngren Posts: 21,315Questions: 26Answers: 4,948
    edited July 19

    Looks like you are following this Editor example. If that is the case then searching for 1( checked ) or 0 ( unchecked ) should work. Open the console of that example and paste this code:

    $('#example').DataTable().column(5).search("1").draw();
    

    Kevin

  • Hildeb67Hildeb67 Posts: 64Questions: 18Answers: 1

    Sorry, I think I misinterpreted
    I wanted to activate/deactivate a checkbox at the top of the filter. Just as shown in the picture

  • kthorngrenkthorngren Posts: 21,315Questions: 26Answers: 4,948

    What is it you want to do when clicking the checkbox in the header?

    If you want to filter the table then create a change event handler for the checkbox. Test if the checkbox is checked and use column().search() as I show above - assuming you are using 1 for checked and 0 for unchecked.

    If you need further help with this then please provide a simple test case with an example of your checkbox column. This way we can understand exactly what you have to offer more specific suggestions.
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

  • allanallan Posts: 63,488Questions: 1Answers: 10,468 Site admin

    I had assumed you'd probably want to use a checkbox to enable the filter. That being the case, my answer still stands - when the filtering checkbox is activated use a function with column().search() to filter the column as I described.

    Allan

  • rf1234rf1234 Posts: 2,988Questions: 87Answers: 421
    edited July 19

    I assume you are using "Editor" because I found this in your code

    class="editor-active"

    If you are using "Editor" this might be useful for you.

    I guess you just want to be able to select whether or not a customer agrees to direct debit ("Bankeinzug"). If that is what you want to do my example is relevant for you.

    This is what my example looks like, code below: A data table with two checkboxes that can be clicked independently of each other. The users can select whether they want to see the respective department's contracts or not, and whether they want to be automatically informed about tasks and events concerning the respective department. Changes are sent to the server to be saved in a database. Pretty much the same as your use case, I guess.

    Simple Editor that only edits the two checkboxes above.

    var ctrDeptSelectionEditor = new $.fn.dataTable.Editor({
        ajax: {
            url: 'actions.php?action=tblCtrDeptSelection'
        },
        table: "#tblCtrDeptSelection",
        fields: [ {
                name:      "govdeptSelected",
                type:      "checkbox",
                options:   [
                    { label: '', value: 1 }
                ],
                separator: '',
                unselectedValue: 0
            }, {
                name:      "govdeptInfo",
                type:      "checkbox",
                options:   [
                    { label: '', value: 1 }
                ],
                separator: '',
                unselectedValue: 0
            }
        ]
    });
    

    Datatable with the two checkboxes and other fields:

    var ctrDeptSelectionTable = $('#tblCtrDeptSelection').DataTable({
        dom: "Bfrltip",
        select: false,
        processing: false,
        ajax: {
            url: 'actions.php?action=tblCtrDeptSelection'
        },
        columns: [
            {   data: "govdeptSelected",
                render: function ( data, type, row ) {
                    if ( type === 'display' ) {
                        return '<input type="checkbox" class="editor-selected">';
                    }
                    return data;
                }
            },
            {   data: "govdeptInfo",
                render: function ( data, type, row ) {
                    if ( type === 'display' ) {
                        return '<div style="text-align:center; float:none;"><input type="checkbox" class="editor-info"></div>';
                    }
                    return data;
                }
            },
            {   data: "ctr_govdept.dept_name" },
            {   data: "userRole",
                render: function ( data, type, row ) {
                    return renderRole(data);
                }
            }
        ],
        columnDefs: [
            // targets may be classes
            {  targets: "hiddenCols", visible: false  }
        ],
        order: [[2, 'asc'], [0, 'asc']],
        buttons: [
                        "selectAllDepts",
                        "selectNoDepts",
            { extend:   "colvis", columns: columns },
        ]
    });
    

    Tying it all together:
    Sending the selection changes to the server using the "Editor" defined above (without opening an editing form):

    $('#tblCtrDeptSelection').on( 'change', 'input.editor-selected, input.editor-info', function () {
        $.busyLoadFull("show");
        var row = $(this).closest('tr');
        ctrDeptSelectionEditor
            .edit( row, false )
            .set( 'govdeptSelected',    row.find('input.editor-selected').prop( 'checked' ) ? 1 : 0 )
            .set( 'govdeptInfo',        row.find('input.editor-info').prop( 'checked' ) ? 1 : 0 )
            .submit(function() {
                ctrDeptSelectionTable.ajax.reload( function(){
                                         $.busyLoadFull("hide");
                                     }, false)
                                     .columns.adjust()
                                     .responsive.recalc();
            })
    
  • allanallan Posts: 63,488Questions: 1Answers: 10,468 Site admin
    Answer ✓

    Here is a simple little example to do what you are looking for: https://live.datatables.net/socirone/10/edit .

    It uses the column().search() option as a function when the checkbox is selected to filter the table.

    Allan

  • Hildeb67Hildeb67 Posts: 64Questions: 18Answers: 1

    Hi Allan, exactly . I want to use a checkbox to enable the filter.
    But I don't know how to add the checkbox in the filter row. Do you have a tip for me here?
    Chris

  • kthorngrenkthorngren Posts: 21,315Questions: 26Answers: 4,948
    edited July 20

    Somewhere you have code to add the text inputs into the header, likely in initComplete. One option is to check the column index. If the index matches the checkbox column then insert the checkbox otherwise execute the code that sets up the text inputs. If you need help with this then please provide a simple test case showing how you are doing this now. Maybe update Allan's example and provide the new link.

    Kevin

  • allanallan Posts: 63,488Questions: 1Answers: 10,468 Site admin

    In my example, I just put the HTML into the cell. Seamed like the easiest option :)

    Allan

  • Hildeb67Hildeb67 Posts: 64Questions: 18Answers: 1

    Hello everyone. I have now created a simple test case. but unfortunately it only works the wrong way. I want to show all the selected ones when I click on the checkbox. otherwise all lines. Can anyone else give me a tip? thanks chris

    https://live.datatables.net/punezazu/117/edit

  • allanallan Posts: 63,488Questions: 1Answers: 10,468 Site admin
                            if (checked && $(row).find('input').prop('checked')) {
                                    return false;
                            }
    

    If the search check is checked, and the check box in the row is checked, then don't show the row. Your logic is wrong. You just need to correct the condition.

    You've used a different method from my example. I'm not sure why, given I showed a working example before, but this one can be corrected to work as well.

    Allan

  • Hildeb67Hildeb67 Posts: 64Questions: 18Answers: 1

    So the following code works for a column with Chrckbox.

              if (checked && $(row).find('input').prop('checked')) {          
              } else if (checked ){ 
                return false;
              }             
               
              return true; 
    
    
    

    But now I have a second column with a checkbox. Now the second column is also filtered. Can you filter this by column? Greetings Chris

    Here my testcase
    https://live.datatables.net/punezazu/121/edit?html,css,js,console,output

  • kthorngrenkthorngren Posts: 21,315Questions: 26Answers: 4,948
    edited July 24 Answer ✓

    You will need to update your if statement. Compare checked with find('input[name="is_hidden"]') and checked2 with the other checkbox. Depending on whether you want an AND search or an OR search will determine how you structure the if statements. Here is one option:
    https://live.datatables.net/punezazu/122/edit

    For performance reasons you might want to make these variable global and set them once in the change event before calling table.draw():

           var checked = $('input[name="chk_box"]').prop('checked');
           var checked2 = $('input[name="chk_box2"]').prop('checked');
           var isChecked = $('input[name="chk_box"]').is(":checked");
           var isChecked2 = $('input[name="chk_box2"]').is(":checked");      
    

    Kevin

  • Hildeb67Hildeb67 Posts: 64Questions: 18Answers: 1

    Great Kevin worked. Thanks for the tip. Chris

Sign In or Register to comment.