开发者

How to filter a table by column using native jQuery

I would like to make use the core jQuery libraries to do as per title. Is it possible to do this with the native jQuery UI library? I prefer开发者_高级运维 not to use plugins as these are not hosted on any CDN (as far as I' am aware).

How can i filter the table by matching the typed input text against the 2nd table column?

<input type="text" id="filter" />
<table>
<tr><td>1</td><td>UK</td></tr>
<tr><td>2</td><td>USA</td></tr>
<tr><td>3</td><td>France</td></tr>
</table>


$('tr td:nth-child(2)') will give you all the 2nd TDs in that table. It is 1-based and will include in its count any non-TD children of the TR.

$('tr td:eq(1)') will also give you all the 2nd TDs in that table. It is 0-based and will only include in its count the TD children of the TR.

Once you wish to do something with the row containing a TD, you can use the TD's parent.


Briefly, you'll put an id on your table element. Then, when you leave the input element (or, in the onclick() handler of a button) you'll do the following:

  • Grab the table element.
  • Find each child in turn, which will be a row, preserving a reference to the element
  • Find the second child of the row and test it against the value of the input to see if it matches (exact match, contains, or whatever kind of test you want to apply).
  • If it matches, set a style indicating it matched onto the row. If not, set a style indicating "not matched" onto the row.

You'll also need a style sheet that makes matched items visible and not-matched items invisible (or uses dark and light text, or whatever visual indicator you want to use for matched & unmatched).

You can make this somewhat more robust if, instead of relying on the second cell on each row to hold the country name you use a class indicator on the cells that hold the country name. Then, instead of "Find the second child" you would "Find the child of class country. Doing this means that your application won't break when you add, remove, or rearrange columns.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜