DataTables search on button click instead of typing in input

Viewed 11483

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?

1 Answers
Related