NSteffen.com

NSteffen.com is where I publish articles and links mostly about the Web and Technology. Feel free to browse around.

Clearing Form Fields on Focus using JavaScript

Download the code from this post

Preview the Script in action

JavaScript gets a bad rap. If you need somebody to blame, find yourself a web developer active in the early to mid-nineties and give him a couple of good jabs. However slowly we are waking up to JavaScript's virtues. In this example, I will show you how to use it to clear the content of an input field when a user selects it, as shown in my sidebar. This is not just JavaScript for the sake of it, but a real usability enhancement.

Giving your input fields a standard value is a good idea, especially if you sacrifice a <label> element for the sake of aesthetics. However using the field then becomes a pain, because the user has to delete your standard text before he can enter his query. So how do we solve this? In 95% of the cases with the help of JavaScript.

Before we get into code, we have to make some decisions about usability. As you probably know, inline Javascript (think <a onclick="someJavaScript()" href="#">) is a big no-no. Using it would mean that for the 5% of the people trawling the web without JavaScript enabled, your form would become useless. So how do we get around this? Enter the DOM.

The Document Object Model

An Example DOM Tree

The DOM makes sense of the clutter that is our code

Think of the DOM like a family tree for your website. At the very top is great-great-great-grandfather <body>, with a lot of child <div>'s, who in turn have offspring of their own in the form of <p>'s and <img>. The DOM lets us select various elements and nodes in a document without having to resort to inline JavaScript. All we need is a way to identify the element we want to modify, like it's own ID, or we have to know what the name of the parent node is. There are various ways of selecting elements using the DOM, but we will stick with out unique ID this time around.

All your input elements should have a unique ID anyways to be used with labels, but this method may serve as your final motivator for doing what you should have been doing all along.

The Form

So, let's have a look at our form. In this example I will use the simple search form as I am using on the right here on this site.

<form>
<label for="search-field">Search for:</label>
<input type="text" name="keywords" id="search-field" value="Search" />
<input type="submit" name="submit" value="Go!">
</form>

Check out the input field. It has a unique ID by which I will be able to identify it later in my JavaScript. However this still falls under the category of being "semantic" since I am not adding an ID merely to be able to use JavaScript. The ID is also for the label element, so screenreaders can easily identify what the input is for.

So, remember that our input has an ID of "search-field"

For the good part: The JavaScript. But first, a quick preview of what we will be using:

getElementById

getElementById is the real star of the show. With its help, we can identify any element in out document tree that has an ID assigned to it. We will be using it to tell JavaScript what input field to apply our effects to, so that it can chose the right one although there may be fifty other fields on the page (I hope you will never encounter such a situation). The syntax for getElementById looks like this:

var variable = document.getElementById("idName");

Pretty self-explanatory. idName would be search-field in out case, and the variable would now hold a reference to that input field which we could use to trigger events, assign classes or add code to the document. With so many possibilities, it's always good to map out what you want to do before you jump into the code.

  1. Make sure the getElementById is supported by the browser
  2. Indentify our input field using its ID
  3. Find out what the default value of our field is
  4. Trigger events depending on wether the user clicks on the field or navigates away from it
    1. When (s)he clicks on it, change the value from it's standard to empty
    2. When (s)he navigates away and has not entered his own data, then display the standard value again

The Execution

Now that we know what we want to do and how we are going to do it, let me show you the magic code. I'll go through it step-by-step afterwards.

function prepareSearchFields() {
  if(!document.getElementById) return false;
  var searchField = document.getElementById("search-field");
  var defaultValue = searchField.defaultValue;
  searchField.onfocus = function() {
    if(searchField.value == defaultValue) {
      searchField.value = "";
    }
  }
  searchField.onblur = function() {
    if(searchField.value == "") {
      searchField.value = defaultValue;
    }
  }
}

If this seems daunting, don't despair. It is a lot easier than you may think. The first line simply creates a function that we can call anytime we want to execute the script. So on to the next line:

if(!document.getElementById) return false;

This is a security check. We are making sure that the browser understands the getElementById property before we continue. If it doesn't (think really old-school browsers) then we simply exit the script using return false and no harm done.

var searchField = document.getElementById("search-field");
var defaultValue = searchField.defaultValue;

Once we have established that we are dealing with a browser capable of executing the script, we use getElementById to grab our search field. We assign it to the variable searchField, so that we have easy access to it later on in the script. On the next line we get the default value of the search field, using the built-in defaultValue property. You can use this with any element that can be assigned a value property.

searchField.onfocus = function() {
  if(searchField.value == defaultValue) {
    searchField.value = "";
  }
}

Now it gets good. We are making use of JavaScripts built in onfocus property. In plain english, the first line of the above code just means 'When somebody clicks on (focuses) the input field that we have assigned to the searchField variable, execute the following function". The function that will be executed in this event is basically an if loop. What it does is it gets the current value of the searchField using the value property. It then checks if the current value is the default value. If it is, it sets the new value of the searchField to blank. As you can see, the value property is read and write, so you can change the value of an element with it as well as read it.

The reason we run the check to make sure that the current value of the field is the default value is very simple: If a user enters a term, navigates away and then focuses on the field again, he will launch our onfocus function again. We don't want to clear the value everytime a user focuses on the field, only if the field still contains the default value since the user will want to change this anyways.

searchField.onblur = function() {
  if(searchField.value == "") {
    searchField.value = defaultValue;
;  }
}

This is basically just the previous example in reverse. The onblur property means that this function will launch any time a user blurs the search field, e.g. clicks away. What we want to do is check wether he has entered his own search term or not, and if not, then we will replace our default value. So the if loop checks if the field is empty, and if it is, then it will re-instate the default value of the field, which we stored as the defaultValue variable earlier on. It prevents the clearing of inputs by the user, which would be frustrating to say the least if you were dealing with large inputs like text areas for comments.

Loading the Script

To keep this script unobtrusive, we don't want to resort to inline JavaScript to tell the function to load. So we use something called window.onload. This little command tells the browser to load a certain function once the page has fully loaded. In our case, the function is called prepareSearchInputs, so the function would look like this:

window.onload = prepareSearchFields;

This command says: "When the window is done loading, call the function called prepareSearchFields". In our external script, we want to add this before we define the function. So here is our final JavaScript code:

window.onload = prepareSearchFields;
function prepareSearchFields() {
  if(!document.getElementById) return false;
  var searchField = document.getElementById("search-field");
  var defaultValue = searchField.defaultValue;
  searchField.onfocus = function() {
    if(searchField.value == defaultValue) {
      searchField.value = "";
    }
  }
  searchField.onblur = function() {
    if(searchField.value == "") {
      searchField.value = defaultValue;
    }
  }
}

Save this script in a file called script.js, so we can call it in any page we want to use it in. Now all you have to do to use this script is to use

<script type="text/javascript" src="script.js"></script>

in the <head> of any of your websites, make sure that your input field has the correct ID assigned to it, and you are good to go.

Demo & Download

If you want to view the script in action, you can view a live version here, or click the link below to download the source files.

Preview the Script in action

Download the code from this post

2 Comments so far

  1. Mike
    September 11, 2008
    #1

    Nice script, but it needs to handle multiple fields.

  2. Nik
    September 22, 2008
    #2

    Hi Mike,

    This will work no problem with multiple input fields. Simply replace getElementById with Robert Nyman’s getElementsByClassName method and you simply have to assign a class to any input field you want this treatment applied to.

Leave a Comment

I never sell, share or give away your E-Mail Address. There is only on rule of commenting here: dont be an asshat. Apart from that you can do what you like.

Remember my personal information

or