Search code examples
javascriptjqueryhtmldatatables

DataTables search on button click instead of typing in input


I would to know if it is possible to move the search function out of an input for a table modified by DataTables. Currently I have a custom input that executes this function:

<script>
    $(document).ready(function() {
        var oTable = $('#staffTable').DataTable();
        $('#searchNameField').keyup(function () {
            oTable.search($(this).val()).draw();
        });
    })
</script>

the input looks like so:

<label for="searchNameField" class="col col-form-label">Name:</label>
<div class="col-sm-11">
    <input type="text" class="form-control ml-0 pl-2" id="searchNameField"
            placeholder="Name" autofocus/>
</div>

What I would like to do is move this to a button. What I thought might be possible is the following:

<script>
    $(document).ready(function() {
        var oTable = $('#staffTable').DataTable();
        $('#searchButton').click(function () {
            oTable.search($(this).val()).draw();
        });
    })
</script>

with the button looking like so:

<button id="searchButton" type="button" class="btn btn-sm btn-success" style="width: 150px">
    <i class="fa fa-search">
        Search
    </i>
</button>

however when I click on the button this does not work. In typing this question I have realised that this is probably because when I click the button, it does not know where to get the filter text from to actually filter the table.

Is there a way I can have a button click that references the input, that then goes and filters the table?


Solution

  • You're right, you need to redefine $(this), which now refers to the button, not the search box:

    $(document).ready(function() {
        var oTable = $('#staffTable').DataTable();
        $('#searchButton').click(function () {
            oTable.search($("#searchNameField").val()).draw();
        });
    
        // EDIT: Capture enter press as well
        $("#searchNameField").keypress(function(e) {
            // You can use $(this) here, since this once again refers to your text input            
            if(e.which === 13) {
                e.preventDefault(); // Prevent form submit
                oTable.search($(this).val()).draw();
            }
        });
    });