Reputation: 2965
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?
Upvotes: 6
Views: 14897
Reputation: 75
This worked for me
let datatable = $('#reg_users').DataTable({
'processing': true,
'serverSide': true,
'serverMethod': 'GET',
'ajax': { 'url':'<?=$url?>adminActions.php?action=FETCH_USERS' },
'columns': [
{ data: 'index' },
{ data: 'user_registered' },
{ data: 'full_name' },
{ data: 'email_address' },
],
search: {
return: true
}
});
$("#reg_users_filter").append(`<button id="searchbtn">Search</button>`);
$("#searchbtn").click(e =>{
datatable.search($('#reg_users_filter input').val()).draw();
});
Upvotes: 0
Reputation: 61793
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();
}
});
});
Upvotes: 10