If you want a simple solution to show and hide some default text for input fields or text areas, this will do it. HTML5 hasn’t fully arrived so until the placeholder value attribute becomes widely supported, we can rely on some good ole JavaScript to get the job done. There are three attributes we need to specify to make this work: value, onfocus and onblur.
Problem One: We want some default text
When you land on the page, you’ll want your input field to have a default value. So let’s start with this:
<input type="text" value="first name" />
This would appear on your web page like this:
Problem Two: We need the default text to disappear on focus
The problem with that however, is that the user has to delete your default text before typing their name. Not friendly. So let’s add some JavaScript to make the default text disappear when the user clicks in the field.
<input type="text" value="first name" onfocus="if(this.value=='first name')this.value=''" />
Notice I added the attribute onfocus
to the input field. The we insert the JavaScript that asks, “If this value equals “first name” (our default text) then this value now equals ” “, or nothing.
Here’s how that would look and work. Click in the field to test it out. Notice the default text disappears.
Our solution isn’t complete yet though… if you didn’t type anything in the field above, and then you clicked outside the field, you’ll notice the default text does not return. To fix this, we need to add some JavaScript for the onblur
attribute
Problem Three: Restore the default text if the field is empty
Here’s the final piece of code necessary to make our input field with default text work as the user would expect:
<input type="text" value="first name" onfocus="if(this.value=='first name')this.value=''" onblur="if(this.value=='')this.value='first name'" />
And that will produce the entry field below. Click in the field, then click outside the field immediately after. The default text should return. Now click in the field, type your name and click outside the field. Your name should still appear!
Special Notes
JavaScript is not always enabled on every computer. Many businesses disable it for security reasons so if you need a rock-solid solution that works without JavaScript, you’ll have to use a different method. However, most computers do have JavaScript enabled so for all intents and purposes, this solution should work just fine for most people.