Remove auto search from text box and search upon search button
There is no reason for adding a new search <input>
, you can reuse the default. The below code resets the default search / filtering that happens when you type in the default <input>
box, then adds two buttons that performs / clear the search / filtering upon click.
var table = $('#example').DataTable({
initComplete : function() {
var input = $('.dataTables_filter input').unbind(),
self = this.api(),
$searchButton = $('<button>')
.text('search')
.click(function() {
self.search(input.val()).draw();
}),
$clearButton = $('<button>')
.text('clear')
.click(function() {
input.val('');
$searchButton.click();
})
$('.dataTables_filter').append($searchButton, $clearButton);
}
})
demo -> http://jsfiddle.net/zuv05qbj/
And as with davids amazing answer, you can also bind the ENTER key to perform the search as well, by invoking the search button click event when it is pressed:
initComplete : function() {
var self = this.api();
var filter_input = $('#'+settings.nTableWrapper.id+' .dataTables_filter input').unbind();
var search_button = $('<button type="button">Search</button>').click(function() {
self.search(filter_input.val()).draw();
});
var clear_button = $('<button type="button">Clear</button>').click(function() {
filter_input.val('');
search_button.click();
});
$(document).keypress(function (event) {
if (event.which == 13) {
search_button.click();
}
});
$('#'+settings.nTableWrapper.id+' .dataTables_filter').append(search_button, clear_button);
}
Works if you have multiple datatables on the page too :) (note the use of settings.nTableWrapper.id
)
Just implemented this and it works great. I added an icon button and some simple flex css to make them inline.
var input = $('.dataTables_filter input').unbind(),
self = this.api(),
$searchButton = $(`<button type="submit"
class="btn btn-inverse dtSearchButton"
id="button_search"
data-toggle="tooltip"
title="Apply Search"
style="padding:0,5px,0,5px"
>
<i class="fas fa-search"></i>
</button>`)
.click(function() {
self.search(input.val()).draw();
}),
$clearButton = $(`<button
type="button"
class="btn btn-inverse dtSearchButton"
id="button_trash"
data-toggle="tooltip"
title="Clear Search"
style="padding:0,5px,0,5px"
>
<i class="fas fa-trash"></i>
</button>`)
.click(function() {
input.val('');
$searchButton.click();
})
$('.dataTables_filter').append($searchButton, $clearButton);
then in css:
.dataTables_filter{
display:flex;
}
final output