Datatables Search Onclick button

Datatables Search Onclick button

Noodles12Noodles12 Posts: 107Questions: 38Answers: 2

I am trying to add an onclick event button "Filter Results" next to "Clear Filters" button. The behavior should be -
once the user selects the dropdown values, the results should be presented only when the user clicks on the button. How can I do this? Thanks.

I tried the following code
$('#myInput').on( 'keyup', function () {
table.search( this.value ).draw();
} );

Test case - https://live.datatables.net/qoxoweca/3/edit

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 20,302Questions: 26Answers: 4,769

    You will need to remove this part of the code:

          .on('change', function() {
            var val = $.fn.dataTable.util.escapeRegex(
              $(this).val()
            );
    
            column
              .search(val ? '^' + val + '$' : '', true, false)
              .draw();
          });
    

    I tried the following code

    Since its a button you will want to use click instead of keyup.

    In the event handler you will need to get the values of each input then perform a column().search() for the appropriate column, for example:

    var val = $('#dropdown1').find('select').val();
    table.column(0).search( val );
    // repeat for all inputs
    table.draw();  // Perform one draw after all the searches are setup.
    

    Kevin

  • Noodles12Noodles12 Posts: 107Questions: 38Answers: 2

    Thanks, Kevin. It worked. However it removed the cascading of the columns. Now it retains all the column values instead of updating the column based upon the selection (see my original example). Is there a way to retain cascading as well?

    This is my updated test case based upon your response.
    https://live.datatables.net/qoxoweca/5/edit

  • kthorngrenkthorngren Posts: 20,302Questions: 26Answers: 4,769
    Answer ✓

    Once you click Filter Results the buildSelect() function will be called, updating the select lists, due to table.draw();. The select lists won't be updated until you perform the search and draw functions.

    Maybe we should go back to your previous test case and remove the .draw() from teh column search, for example:

            column
              .search(val ? '^' + val + '$' : '', true, false)
              //.draw();
          });
    

    And call buildSelect() using the search event, for example:

      table.on('draw search', function() {
        buildSelect(table);
      });
    

    Update the click event handler to call draw(), for example:

    $('#myInput').on( 'click', function () {
      table.draw(); 
    } );
    

    Updated test case:
    https://live.datatables.net/wutosiyi/1/edit

    Kevin

  • Noodles12Noodles12 Posts: 107Questions: 38Answers: 2

    This works great. Thankyou so much!

Sign In or Register to comment.