I'm trying to filter a table with Javascript. The code I'm using is the following:
var $rows = $('tr').not('#tr');
$('#search').keyup(function() {
var val = '^(?=.*\\b' + $.trim($(this).val()).split(/\s+/).join('\\b)(?=.*\\b') + ').*$',
reg = RegExp(val, 'i'),
text;
$rows.show().filter(function() {
text = $(this).text().replace(/\s+/g, ' ');
return !reg.test(text);
}).hide();
});
it works fine with a static table like this one:
<table id="table">
<tr id="tr">
<th><h4>uuid</h4></th>
<th><h4>xValue</h4></th>
</tr>
<tr>
<td><p>stuff2</p></td>
<td><p>foo2</p></td>
</tr>
<tr>
<td><p>stuff</p></td>
<td><p>foo</p></td>
</tr>
</table>
but when I create the table dynamically from a json with ajax, the filtering script is not working anymore. How can I solve this?
Here's the code for table generation from json I use:
var url = 'https://api.github.com/users/mralexgray/repos';
$.ajax({
type: 'GET',
url: url,
async: false,
contentType: "application/json",
dataType: 'json',
crossDomain: true,
success: function(data) {
drawTable(data);
},
error: function(e) {
console.log(e.message);
}
});
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
function drawRow(rowData) {
var row = $('<tr/>')
$("#table").append(row); //this will append tr element to table... keep its reference for a while since we will add cels into it
row.append($("<td><p>" + rowData.id + "</p></td>"));
row.append($("<td><p>" + rowData.name + "</p></td>"));
row.append($("<td><p>" + rowData.lastName + "</p></td>"));
row.append($("<td><p>" + rowData.private + "</p></td>"));
row.append($("<td><p>" + rowData.fork + "</p></td>"));
row.append($("<td><p>" + rowData.description + "</p></td>"));
row.append($("<td><p>" + rowData.size + "</p></td>"));
}
Your defining $rows
before your search function. Adding new rows dynamically after its been set wont change the value of $rows
. Try defining it within the search function
$('#search').keyup(function() {
var $rows = $('tr').not('#tr'); // set value here
..