Clear Default Input Box Text on Click with jQuery

Check out the demo

You know those search boxes that say “search here” and you go to click them and the text goes away? It’s a nice little feature and is really simple with jQuery.

Here is the simple script to take you through the ages:

The HTML

	<form>
		<input type="text" name="search" id="search_box" value="search here!" />
		<input type="submit" value="Search" />
	</form>

Here we simply create a form with a textbox with an id of “search_box”. This id will help us reference it later with jQuery. ALSO take note that the value attribute is set to search here!.

The jQuery

Now simply place the following in your <head> tags and call it good.

<script type="text/javascript">
  // Some simple jQuery to remove the default search value when the user clicks the box
  $(document).ready(function() {
	  	$search_box = $("#search_box");

	  	// If the user clicks the input box and the text is "search here!",
	  	//    set it to blank
		$search_box.click(function() {
			if( $search_box.attr("value") == "search here!" ) {

				// Set it to an empty string
				$search_box.attr("value", "");
			}
		});
  });
</script>

That’s it! Basically, we find the search box by its id with $(“#search_box”) and then clear its value attribute if the string we compared to is the default search string



Share this post


facebooktwittergoogle_plusredditpinterestlinkedinmail

Tags:

Comments are closed.