jQuery Search And Highlight
I was sitting in class and wanted to come up with some simple way to add a inline same page ajax search on a website. I came across the jQuery selector :contains(text), check out the documentation for this. Now the to the final product, lets check out the demo. We are going to have our main components for this:
- The form (1 input and submit)
- The :contains selector
- The fadeIn() effect
- The addClass()
The approach for the code is going to be like
- User will enter term in form
- Save data to a variable
- Place variable in to :contains selector
- Fade in the highlight class (using fadeIn() and addClass())
See, there it is simple? Just about! Next lets take a look at the jquery
$(document).ready(function(){
$("#submit").click(function(){
// start variables as empty
var term = "";
var n = "0";
// hide the results at first
$("p.results").hide().empty();
// grab the input value and store in variable
term = $('#term').attr('value');
console.log("The value of term is: "+term);
$('span.highlight').each(function(){
$(this).after($(this).html()).remove();
});
if($('#term').val() == ""){
$("p.results").fadeIn().append("Enter term in field above");
$('#term').fadeIn().addClass("error");
return false;
}else{
$('div.container :contains("'+term+'")').each(function(){
$(this).html($(this).html().replace(new RegExp(term,'g'), ''+term+''));
$(this).find('span.highlight').fadeIn("slow");
});
// how many did it find?
n = $("span.highlight").length;
console.log("The there is a total of: "+n);
if(n == 0){
$("p.results").fadeIn().append("No results were returned");
}else{
$("p.results").fadeIn().append("Returned: "+n+" result(s) for the search term of: "+term+".");
}
return false;
}
});
});
And now the HTML structure:
Welcome to my site!
Kind of a late start here today. I have been reading this book online lately called Learning Rails that covers version 2.0 unlike most of the books that are out there. I was able to follow and understand this book to guide me through Rails and its done wonders. I haven’t seen to many typos and the code is easy to understand. There is one chapter that floats away from the rest and its a bummer because its the rails and Ajax section, but besides that, its a great learning tool. I released an Illustrator tutorial yesterday on creating nautical floatie buoys, a simple and straight forward tutorial. Let me know what you think! I was talking to Richard Worth and I am going to be writing a post on working with the jQuery UI and implementing the draggables and selectables together, which is very interesting. I have tried this approach about a year ago with Worth, but it was kind of buggy, Richard released a working version that I will be covering and hopefully try to work it in to the UI API. So stay tuned for that post. I am also going to be working on some other posts overtime working with jQuery and various ajax methods and functions. Loading data, displaying data, and all sorts of other goodies I have been making small modifications to the site, as you can see I added in the top menu bar, and I know it is broken in IE, im on it! I will be working in a home made small jQuery menu to bring down subcategories of what you see up top. Have an idea for a post that you want to see on here? Let me know
Now that we have the outline of the code that we will be using, lets breakdown the bulk of it. If you notice we have the click event handler, which means that the code will not execute until someone has pressed the submit button. The first couple of lines take care of initializing of the script.
var term,n;
// hide the results at first
$("p.results").hide().empty();
// grab the input value and store in variable
term = $('#term').attr('value');
console.log("The value of term is: "+term);
I have commented the code for it is easier to retain the information when you come back for future reference. So the first two lines just sets two variables term and n. The next line hides the p.results element and empties it, our results after form submission will be loaded in here. Lets come back to the variable that we created we set term to whatever the value that was entered in the input box. We are going to use the console.log to make sure our variable is receiving the data.
Lets make it highlight.
The next section of the code is going to to reset the and remove all span.highlight classes for when you enter another term you will only have the new results entered via the form and not both old and new terms.
$('span.highlight').each(function(){
$(this).after($(this).html()).remove();
});
The code is going to run through each of the span.highlight and manually remove the tag. This will be executed every time the form is submitted. Its main purpose is to clear the results. The next part is a quick validation making sure that the form cannot be submitted without some type of data, this is the first section of the conditional:
if($('#term').val() == ""){
$("p.results").fadeIn().append("Enter term in field above");
$('#term').fadeIn().addClass("error");
return false;
That part reads if the element #term returns empty, then fadeIn() and append() text. The line after adds the class error to the input field to give us as red border indicating there has been some type of error. The return false is in place for the form is not submitted. The latter of the conditional will look like:
}else{
$('div.container :contains("'+term+'")').each(function(){
$(this).html($(this).html().replace(new RegExp(term,'g'), ''+term+''));
$(this).find('span.highlight').fadeIn("slow");
});
This occurs when there is data in the input, and it takes the term and we find it using :contains, it runs through each element and replaces the text by wrapping a span tag with the class highlight around the term. After, it finds each of those elements and fades them in.
Displaying our results
The last part is going to display our results, it is going to tell us:
- The term we searched for
- How many results were found
Lets take a look at the code:
// how many did it find?
n = $("span.highlight").length;
console.log("The there is a total of: "+n);
if(n == 0){
$("p.results").fadeIn().append("No results were returned");
}else{
$("p.results").fadeIn().append("Returned: "+n+" result(s) for the search term of: "+term+".");
}
return false;
}
});
});
We are going to retrieve the number of results returned by storing it in the variable n and searching for every span.highlight element and using .length() to retrieve the amount. I have added the console.log() to see what is going on in the back end.
The next part is a simple conditional if n returns no results, then fadeIn() and append() text – “No results were found.” If results were found, then do the same but tell us how many were found and what term the user searched for.
There you have it, a very quick and clean same page search and highlight using jQuery. If you have any recommendations or other features you would like to see, drop a comment or email me. What did you think of it ?
other related posts...
- Combining Selectables And Draggables Using jQuery UI
- Use jQuery To Submit Form To PHP/MySQL
- How to use jQuery to Serialize Ajax Forms
- jQuery Timeout Function
- How to load data using JSON/PHP using jQuery

wow.. very useful code. thxs
Hello,
very fine code. But if there are hrefs these links will be destroyed after parsing the text/html code. Is there a possibility not to highlight the search term inside a link?
Greetings, seima
Hey,
Im sorry I am kind of confused by what you mean. So if you have a link on your page you dont want the script to highlight it?
Ryan
Hey Man,
Looks ace in FF, but explodes in IE 7(on XP)
bummer
[...] View Tutorial No Comment var addthis_pub=”izwan00″; BOOKMARK This entry was posted on Monday, June 8th, 2009 at 4:14 am and is filed under Javascript Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. [...]
I implemented something similar to this but unfortunately “contains:” is case sensitive … I’m looking for something else to provide real time filtering of items that isn’t case sensitive.