Reputation: 3664
My dataTable version is 1.10.4. I'm populating the datatable by passing the Javascript sourced data
var dataSet = [
['Trident', 'Internet Explorer 4.0', 'Win 95+', '4', 'X'],
['Trident', 'Internet Explorer 5.0', 'Win 95+', '5', 'C']
//----
];
$(document).ready(function () {
$('#demo').html('<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>');
$('#example').dataTable({
"data": dataSet,
"columns": [
{ "title": "Engine" },
{ "title": "Browser" },
{ "title": "Platform" },
{ "title": "Version", "class": "center" },
{ "title": "Grade", "class": "center" }
]
});
});
Now I have a search input to filter the table based on the input. I'm trying to get the filtered data that returns and rendering in the table.
For example, If the users search input is 'C' then i should get filtered data
var dataSet = [ ['Trident','Internet Explorer 5.0','Win 95+','5','C'] ];
Is there any standard way of getting filtered data in datatable?
if not I want to get the array on key up
$( "#searchInput").on( 'keyup change', function () {
// get the filtered JavaScript data
});
Please refer to JSFIDDLE HERE
Upvotes: 1
Views: 2065
Reputation: 85598
You can use the search.dt
event for this (here assuming you have stored the instance of the dataTable in a table
variable) :
$("#example").on('search.dt', function() {
var filteredRows = table
.api()
.rows( {order:'index', search:'applied'} )
.data();
for (var i=0; i<filteredRows.length; i++) {
console.log(filteredRows[i]);
};
});
This will echo all the filtered rows out in the console in the same order as they are declared in your dataSet
object :
["Gecko", "Firefox 3.0", "Win 2k+ / OSX.3+", "1.9", "A"]
["Gecko", "Camino 1.0", "OSX.2+", "1.8", "A"]
["Gecko", "Camino 1.5", "OSX.3+", "1.8", "A"]
["Gecko", "Netscape 7.2", "Win 95+ / Mac OS 8.6-9.2", "1.7", "A"]
etc. Note, if you instantiate your table with DataTable()
instead of dataTable()
you will not need the api()
reference.
forked fiddle -> http://jsfiddle.net/fpbokb68/
see https://datatables.net/reference/type/selector-modifier with examples of different ways to extract rows out of a dataTables instance.
Upvotes: 2
Reputation: 6734
This is an example search for you; you can delete button and add onchange to your area.
Search <input type="text" id="searchText">
<input type = "button" onClick="searchAndUpdate()">
This is function;
function searchAndUpdate(){
var searchText = $('#searchText').val();
var resultTable = [];
dataSet.forEach(function(element) {
var objString = JSON.stringify(element);
if(objString.indexOf(searchText)!=-1){
resultTable.push(element);
}
});
console.log(resultTable);
//update your table
}
Note: You have to update your table. Here EXAMPLE.
Upvotes: 0