How to Clear Input Field on Click JavaScript

By Beacon News | Published September 11, 2013 | Categories: Web Development

As we all know, we are constantly learning new and better ways of doing things and today I learned an improved method for clearing a search box to make it more universal and easy to implement.

Let’s first take a look at what we were using:

		if(jQuery(this).val() === 'Search'){
		if(jQuery(this).val() === ''){

//Directions for use
//Replace the ID #searchBox with the id of your search input field  
//Replace the word 'Search' with the desired default input field text

We typically used this to replace our even older method that involved 2 other JavaScript files… yes this replaced 2 files!! We simply add it to our normal global scripts file (scripts.js), update the ID/Class for the sites search field and call it a day!

For the most part this has worked great… until today! I am currently working on a site that we are making responsive and in order to do that efficiently I am cleaning up as much extra as I can. We want to minimize everything we can to ensure that with this enhancement there are no effects on page load. So I go to add it as I normally would but to be sure I first searched the site for all instances of the ‘clearDefault’ class that the (even older) JavaScript was using. I mainly did this so I knew what to test once I put the new code in place but instead I was in for a pleasant surprise of multiple instances with multiple values to replace! So I had to take a step back and reevaluate our current solution to include other scenarios.

I did have a few variations but this is what I settled on:

	jQuery('input:text, textarea').focus(function(){
		if(this.value === this.defaultValue){
			this.value = '';
	jQuery('input:text, textarea').blur(function(){
		if (!this.value.length) {
			this.value = this.defaultValue;

The differences are as follows:

  • Will apply to all input and textarea fields vs. needing a ‘clearDefault’ class
    • Pros: less HTML for page, consistency throughout site
    • Cons: the unseen situation where you would not want this JavaScript to apply
  • Uses original value of field to default back to vs. having to manually set it in the JavaScript
    • Pros: less setup, can be used globally on all fields no matter what the value is
    • Cons: the unseen situation involving browser issues with ‘defaultValue’

Note: This does require jQuery on the page but for the most part all of our sites already have jQuery so we decided to use it where we could.


I am not saying this is the only or absolute best way to handle this but it is the solution that fit our needs.  If anyone has any suggestions on how this could be improved or done in a more efficient way please comment below!

Contact Us To Find Out More

Have questions? Need help? Contact us and we'll be in touch soon!

* Required

164 Thatcher Road
Greensboro, NC 27409
Map and Directions

Sales & Marketing