Quick Tip #2 – Bringing Back Search with jQuery

This is something I use on all my projects now. It’s designed for a search box, but can be used with any sort of input field.
The great thing about this is that the field value “Search” will only come back onBlur if the field is empty (or doesn’t say “Search”). So if you started typing something it won’t erase your text, which is something that has always irritated me about search boxes.
Anyway, I’ve been sitting on this post for a while, but I really wanted to get it out. So here it is:
XHTML
<div id="search">
<form method="post" action="">
<label for="field">search</label>
<input type="text" id="field"/>
<button type="submit">go</button>
</form>
</div><!--/search-->jQuery
$("#search input").focus( function() {
if ($(this).val()=="Search") {$(this).val("");}
});
$("#search input").blur( function() {
if ($(this).val()=="") {$(this).val("Search");}
});The word “Search” in the jQuery is case sensitive, so watch out for that.
Both comments and pings are currently closed.
« 10 Tips to Create a More Usable Web | 10 Videos for the Web Community »
|
Comments (6)
|
Thanks for the tip! Will use it on my next project
Hey! that’s cool, I didn’t know how that was done. Thanks!
Nice one Tim,
I love the re-design of the site.
Thanks man, much appreciated
One little mini tip would be to chain the events, so you don’t have to run the selector again:
$("#search input")
.focus( function() {
if ($(this).val()=="Search") {$(this).val("");}
})
.blur( function() {
if ($(this).val()=="") {$(this).val("Search");}
});
Nice addition, thanks Chris