I wrote a few lines of jQuery code, but don't know how to realize this in plain JavaScript. That output:
echo "<tr id='perf_row' class='table_header_tr' name='tr_$row_fio_perf[0]'>
<td class='table_header_td' name='td_$i'>
$i
</td>
<tr>";
search input. When user inputs chars, table rows (output higher) must hide and show only what matches the search word.
<input type="text" onkeyup="showPerformers();" id="ShowSearchPerformers">
function showPerformers(){
var search_login = $('#ShowSearchPerformers').val();
search_login = search_login.toLowerCase();
$('tr[name^=tr_]').hide();
var search = 'tr[name*=' + search_login+']';
$(search).show();
}
How to write this function in JavaScript, not jQuery?
1 Answer 1
I would suggest a different approach all together, but based on your code, and not over-complicating things too much:
<input type="text" onkeyup="showPerformers(this,event);" id="ShowSearchPerformers">
Passing the input element to the function saves a DOM scan (getElementById, or in jQuery $('#id')). Also passing the event object might prove useful given time.
function showPerformers(search_login,e)
{
search_login = search_login.value.toLowerCase();
var table = document.getElemebtById('YourTblId');
var row = table.getElementsByTagName('tr');
var nameSearch = new RegExp('^tr_' + search_login);
for (var i=0;i<row.length;i++)
{
if (row[i].name.substr(0,3) === 'tr_')
{
row[i].style.display = '';//make previously hidden rows visible again
if(!row[i].name.match(nameSearch))
{//row name starts with tr_, but not tr_[searched number]
row[i].style.display = 'none';
}
}
}
}
If I'm not mistaken, this should work, and perform as you expect it to. It does need some fine-tuning though, but I wouldn't want to spoil your fun :). Just a tip, as it now stands, you have no guarantee that the user-input is numeric: entering a would hide all rows, and show none, for example. You could fix that by either:
value.replace(/[^0-9]/g,'');//leaves only numbers
Math.floor(parseFloat(value));//Math.floor(parseFloat(' 123.1s')) --> 123
Just play a little, BTW this site is a great sandbox for stuff like this
querySelectorAllwould be of great help here, yet it won't work in IE7.