I have encountered this code
$("#search").keyup(function(){
var val = $.trim(this.value).toLowerCase();
$("table > tbody > tr:gt(0) ").hide();
if(val.length){
$("table > tbody > tr:gt(0) > td").filter(function(){
return this.innerHTML.toLowerCase().indexOf(val) >=0;
}).parent().show();
} else $("table > tbody > tr:gt(0)").show();
});
For Querying a a table in jQuery. here's the HTML markup
<p>
<input id = "search" type = "text">
</p>
<table id ="accounts">
<tr>
<th>Username</th>
<th>Password</th>
</tr>
<tr>
<td>Metasm</td>
<td>password1992</td>
</tr>
<tr>
<td>superadmin</td>
<td>adminpassword</td>
</tr>
<tr>
td>skyrocketeer</td>
<td>thejetsons</td>
</tr>
</table>
Basically it works. but the I am very confused with regards to the jQuery code.
My Question: in this part of code
$("table > tbody > tr:gt(0) > td").filter(function(){
return this.innerHTML.toLowerCase().indexOf(val) >=0;
}).parent().show();
What does this part specifically do? and what does it return?
$("table > tbody > tr:gt(0) > td")
- This lines of code states that you want all <td>
elements within a <table>
element that are in a <tbody>
element, who's <tr>
element's index is greater than 0
(ie - skip the first row. gt()
is simple Greater Than). The >
selector states that we only want elements in the first level of children - we don't want to drill down further than the first set of child elements.
The .filter()
function will reduce the set of matched elements to those that match the selector or pass the function's test.
The conditional statement here is looking for a certain index of a search string val
, within the innerHTML of each element.
this.innerHTML.toLowerCase().indexOf(val) >=0
So what this is saying (remembering that we are iterating over all the elements we found from our first selector) is that we are looking for an occurance of the string val
within the innerHTML
of the element. The innerHTML is also being passed through the toLowerCase()
function, who's name suggests is function - converts all characters to their lowercase form.
Phew...Now after all this we are left with a certain list of elements. Elements that met all of our specifications above. For each of these elements, the code will locate their parent (remember we are talking about <td>
elements, so their parents should be <tr>
) with the .parent()
function and display them on screen with the .show()
function.
For the first selector - $("table > tbody > tr:gt(0) > td")
, I find sometimes its easier to read it backwards (in your mind) to understand the hierarchy...
Return the -
<td>
elements,<tr>
elements (but not the first one),<tbody>
element<table>
element.Now for some sample input and output:
val
is "jet", the function would display the last <tr>
- the one with the string - thejetsons
.val
is "password", the function would display the two <tr>
elements in the middle. The ones that contain "password1992" and "adminpassword".