Reputation: 882
I am trying to search records based on inputs that the user puts from the text boxes in the table. It is not showing the records properly. Please help. I am trying to get the records in the onchange() of respective text-boxes however; its not working.
Here is my JSFiddle:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
<script>
$(function () {
var table = $("#datatable").DataTable();
$('#search-id').on('change', function(){
console.log("id called");
table
.column(1)
.search(this.value)
.draw();
});
$('#search-fname').on('change', function(){
table
.column(2)
.search(this.value)
.draw();
});
$('#search-lname').on('change', function(){
table
.column(3)
.search(this.value)
.draw();
});
$('#search-mobile').on('change', function(){
table
.column(4)
.search(this.value)
.draw();
});
});
</script>
<table id="datatable" class="table table-bordered table-striped">
<thead>
<tr>
<td><input type="text" id="search-id" placeholder="Search ID"></td>
<td><input type="text" id="search-fname" placeholder="Search name"></td>
<td><input type="text" id="search-lname" placeholder="Search surnam"></td>
<td><input type="text" id="search-mobile" placeholder="Search mobile"></td>
</tr>
<tr>
<th>Profile id</th>
<th>Name</th>
<th>Surname</th>
<th>Mobile#</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Profile id</th>
<th>Name</th>
<th>Surname</th>
<th>Mobile#</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>1</td>
<td>John</td>
<td>Keller</td>
<td>18411564</td>
</tr>
<tr>
<td>2</td>
<td>Donald</td>
<td>Duck</td>
<td>49816156</td>
</tr>
</tbody>
</table>
Upvotes: 2
Views: 130
Reputation: 337560
Your code is working fine, the issue is because the column indexes are 0
based, so you're looking for the value in the wrong column, for example:
$('#search-id').on('change', function() {
table
.column(0) // id column == 0, not 1
.search(this.value)
.draw();
});
Also note that you can completely DRY up your code with the use of data-*
attributes and a single event handler based on a class:
<tr>
<td>
<input type="text" class="search" data-column="0" placeholder="Search ID">
</td>
<td>
<input type="text" class="search" data-column="1" placeholder="Search name">
</td>
<td>
<input type="text" class="search" data-column="2" placeholder="Search surname">
</td>
<td>
<input type="text" class="search" data-column="3" placeholder="Search mobile">
</td>
</tr>
var $table = $("#datatable").DataTable();
$('.search').on('keyup change', function() {
$table
.column($(this).data('column'))
.search(this.value)
.draw();
});
Upvotes: 4
Reputation: 61
You also will need to use a 'keyup' listener. Change only occurs in the text input fields when they lose focus.
Upvotes: 1