Table header input fields automatically sort on enter key
Table header input fields automatically sort on enter key

I'm using a routine that sets the th
html content to an input
dialog to allow for filtering on specific fields on ajax source data. Searching works great except column order is being triggered when the user hits enter, causing duplicate ajax requests and ordering columns when no sort was requested.
The resulting HTML for the th
field looks like:
<th class="sorting_asc" tabindex="0" aria-controls="apTable" rowspan="1" colspan="1" style="width: 185px;" aria-label="Manufacturer: activate to sort column descending" aria-sort="ascending">
<input placeholder="Manufacturer" class="column_search" onclick="stopPropagation(event);" type="text">
</th>
With column input setup:
function setupColumnSearch(table, columnTitles) {
$(table.table().header()).find('th').each( function () {
var title = $(this).text();
if (columnTitles.indexOf(title) > -1)
$(this).html( '<input type="text" placeholder="'+title+'" class="column_search" onclick="stopPropagation(event);"/>' );
} );
/* Setup column-level searches on enter key only. */
table.columns().every( function () {
var column = this;
$( 'input.column_search', this.header() ).on( 'keyup', function (e) {
/* Ignore all keyup events except for return keys */
if(e.type === 'keyup' && e.keyCode !== 10 && e.keyCode !== 13) return;
if (column.visible()) {
table.column( column.index() ).search( this.value ).draw();
}
} );
}
Is there any way to ignore order when the input
field is entered?
This discussion has been closed.
Answers
JSBin Example: https://jsbin.com/nupogip
@grutz Did you ever figure out the solution for this? I am doing something very similar and also need to disable sorting everytime the enter key is detected on the input. I also used stopPropagation(event) but no avail.
Use the keydown event instead of keyup. This gives you a chance to
preventDefault
andstopPropagation
. See this bin - https://jsbin.com/zumudicupu/1/edit?html,js,output@rduncecb Your example doesn't stop the sorting from happening when the enter key is pressed.
Hi @AndrewAlberg ,
I don't think that's possible if you have a single header. I normally suggest you use two headers, like this example, if you want to put input elements in the header cells and not affect the ordering.
Cheers,
Colin
Hi, anybody got a solution for this issue ?
The best solution is the one Colin mentioned. Use two header rows. One for Datatables to bind its events like sorting too and the other for the search input. This is controlled through the use of
orderCellsTop
. By usingorderCellsTop
you can place the sorting in the top header and the search inputs in the second header or vice versa.Kevin
Actually @rduncecb is right. Use keydown instead of keyup (the jsbin wasn't updated). - https://jsbin.com/qejiluhito/edit?html,js,output