Reputation: 1609
Given the following table (a slightly modified version of this one at w3schools) but searches all columns, I'm getting the error that searchAttorneys is not defined at HTMLInputElement.onkeyup
when entering a value in the textbox. Also, how can I keep the table headers from disappearing when searching the table?
HTML
<input type="text" id="search-attorneys" onkeyup="searchAttorneys()" placeholder="Search for names.." title="Type in a name">
JS
function searchAttorneys() {
var input, filter, table, tr, td, i;
input = document.getElementById("search-attorneys");
filter = input.value.toUpperCase();
table = document.getElementById("attorneys");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
tds = tr[i].getElementsByTagName("td");
var found = false;
for (j = 0; j < tds.length; j++) {
td = tds[j];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
found = true;
break;
}
}
}
if (found) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
JSFIDDLE: LINK
Upvotes: 2
Views: 9054
Reputation: 708
HTML
<input type="text" id="search-attorneys" placeholder="Search for names.." title="Type in a name">
Javascript
$(document).ready(function(){
$('search-atorneys').on('keyup', function(){
var input, filter, table, tr, td, i;
input = document.getElementById("search-attorneys");
filter = input.value.toUpperCase();
table = document.getElementById("attorneys");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
tds = tr[i].getElementsByTagName("td");
var found = false;
for (j = 0; j < tds.length; j++) {
td = tds[j];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
found = true;
break;
}
}
}
if (found) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
});
});
execute from inside js and not from inside html is mostly the better way.
Upvotes: 1
Reputation: 3020
Set your jsfiddle javascript load type to nowrap (either one). The other 2 (onload/ondomready) will wrap the function inside another function, making it invisible to your inline onkeyup.
Upvotes: 0