>> GreenByte.info By Nick Tong (quiksilv) | Supported by: TalkWebSolutions.co.uk

Restore default input value with javascript onblur

I need to be quite strict on the space I'm using with a form, so I need to put the search term in the text box as apposed to a label. This is fine, but what annoys me when I find form like this is that one has to delete the value in the text box when you click on it. Well this is easy to fix just add a this.value='' to the onfocus event:

Search for:
<input type="text" name="keyword" id="keyword" value="Keyword" onfocus="this.value='';" />

The problem is that if you don't change any text and click away from the text area, it is left blank. This can cause some issues for screen readers as well as making the screen a little confusing.

A way to fix this is to restore the original value when the user blurs of the text box:

Search for:
<input type="text" name="keyword" id="keyword" value="Keyword" onfocus="this.value='';" onblur="if(this.value==''){this.value='Keyword'};" />

To take this one step further, one can make sure that the text box value is only made blank if the default value is current:

Search for:
<input type="text" name="keyword" id="keyword" value="Keyword" onfocus="if(this.value=='Keyword'){this.value=''};" onblur="if(this.value==''){this.value='Keyword'};" />


 
Comments
Dominic Mitchell's Gravatar I find that using onfocus="this.select()" is a better way of dealing with this. It means when you enter the text field, you can just start typing to overwrite it. But if you tab out of it, then the text stays intact. I freely admit that I have no idea how this might interact with a screen reader.
# Posted By Dominic Mitchell | 13/03/07 21:42 | Report abusive comment
BlogCFC was created by Raymond Camden. This blog is running version 5.5.1.