Highlight a row in a table based on a search string using jQuery

I had recently posted on changing the border color when the user hovers over a table. A user mailed me back asking if it was possible to highlight only a cell based on a search string passed. Here's how to do so:

The trick is to use selectors http://docs.jquery.com/Selectors

<html xmlns="http://www.w3.org/1999/xhtml">

<
head >
<
title>Search and highlight Border Color on Hover</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>

<
script type="text/javascript">
$(document).ready(function() {
$(".someClass").hover(
function() {
$("td:contains('Row 1, Column 1')").css("border", "Solid Brown 1px");
},
function() {
$("td:contains('Row 1, Column 1')").css("border", "");
});
});
</script>
</
head>

<
body>
<
form id="form1" >
<
table id="tblOuter" class="someClass" style="width:50%">
<
tr>
<
td>Row 0, Column 0</td>
<
td>Row 0, Column 1</td>
<
td>Row 0, Column 2</td>
</
tr>
<
tr>
<
td>Row 1, Column 0</td>
<
td>Row 1, Column 1</td>
<
td>Row 1, Column 2</td>
</
tr>
<
tr>
<
td>Row 2, Column 0</td>
<
td>Row 2, Column 1</td>
<
td>Row 2, Column 2</td>
</
tr>
</
table>
</
form>
</
body>
</
html>

Live Demo

So when the user hovers over the table, only the cell with Row 1 Column 1 text gets highlighted. The text has been hardcoded here but can easily be replaced to accept the value from a textbox.




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

2 comments:

Anonymous said...

WAY TO NOT POST A DEMO OR AN EXAMPLE I WILL USE THE MAGIC POWER OF IMAGINATION

Suprotim Agarwal said...

Thanks for your comment. A link to the demo has been added