HTML forms and onclick/onfocus

Update: This post is ancient, with CSS3 and HTML5 there are much nicer ways to achieve similar things.

When you use HTML forms it is often desirable to pre-fill some input fields. Your idea could be that you want to give your visitors some clue to what they're supposed to fill in.

This looks nice, for example:

When the user clicks into the field you'll want to remove the clue. The obvious way to do this is to add an onclick JavaScript command:

 
<form>
	<input onclick="this.value=''" type="text" value="Your email">
</form>

The user can still access the input field through other means than clicking. He can use the tab key for example. That's why usually the onfocus event is more useful:

 
<form>
	<input onfocus="this.value=''" type="text" value="Your email">
</form>

This seems to work nicely. However there's still a problem. When a user fills in his email address, reads a little more on your site and clicks the input field again, his address will be removed again! So to make sure this doesn't happen we add a little check for the content of the field:

 
<form>
	<input type="text" value="Your email" onfocus="if (this.value == 'Your email') {this.value=''}">
</form>

And here it is:

Restore default value if nothing is entered

Ok, now this is working. However, when your visitor decides not to input any data, the field stays empty. If you have no label for the input he or she might forget what the field was for. We fix this by restoring the default value when the input field is left:

 
<form>
	<input type="text" value="Your email" onblur="if(this.value == '') { this.value='Your email'}" onfocus="if (this.value == 'Your email') {this.value=''}">
</form>

Thanks to Ray for his example linked in the comments.

Select onclick

But sometimes this isn't the best solution. It could be more desirable to highlight the content of the input field if you're offering some kind of search. The user may not want to start a new search but to modify the existing one. By highlighting the input field the user can choose to either empy it by starting to type or to modify it by using the arrow keys.

 
	<form>
		<input onclick="this.select()" type="text" value="Your previous searcj">
</form>

Using onclick here makes sense as the content is selected anyway if you use the tab key to access it. Webkit-based browsers also don't handle onfocus nicely.

Dynamic input color

This is a little advanced. Let's assume you want the default value to be in a different color and change it onclick. This is one working solution:

 
<form>
	<input style="color: #f00" type="text" value="Your email" onblur="if(this.value == '') { this.style.color='#f00'; this.value='Your email'}" onfocus="if (this.value == 'Your email') {this.style.color='#0f0'; this.value=''}">
</form>

Keep in mind that this might create problems when you reload the page. Some browsers will remember the value of the input field, and the color will be different even though the field does not contain the default value. Fixing that is beyond the scope of this post. See onload and domready events.

51 comments

  1. avatar
    wrote this comment on

    That is great. Now additional question if I may.

    If I want "Your email" value to return back on page load, what do I change?

    Thanks,
    William

  2. avatar
    wrote this comment on

    I guess you could use an onload or onunload event. Something like
    <pre>window.onload=function()</pre> Not sure why you would want to do that though.

  3. avatar
    wrote this comment on

    i've got it all set, but i want the default text to be grey, and then when the user types in the input, I want the new text top be black....

    Can you help me?

    here's my form
    <strong>Edit: remove 404</strong>

  4. avatar
    wrote this comment on

    You can add this.style.color='#000'; before the if(). I like how you reset the input value to the default if nothing is entered, I think I will add that to my post. That would have solved William's problem above too. And I'll add the color change too. Good comment :-)

  5. avatar
    wrote this comment on

    Another note, if you reload the page the input value is still what the user entered, but the text would remain grey.
    Fixing that would probably be a little tricky, you'd need an onload or some ondomready event that checks the content of all inputs and changes the color.
    But that's only required if you want to make a perfect form.

  6. avatar
    wrote this comment on

    I cannot seem to get that this.style.color=’#000′; to work?

    original input

    can you show me exactly where to put it - thank so much

  7. avatar
    wrote this comment on

    That's strange..
    When I reload the page it resets to the default.

  8. avatar
    wrote this comment on

    onfocus="this.style.color='#000'; if (this.value == 'Who is the Skater?') {this.value=''}"

  9. avatar
    wrote this comment on

    It's not working for me.
    I'm on a Mac
    checking with safari 3 and firefox 2.

    When I add the this.style.color=’#000′; snippet, not only does it not change the font to black-- but it also removes the functionality of the "this.value" ...

    AIM=onepercentposse

  10. avatar
    wrote this comment on

    Ok i now see in Firefox that reloading the page leaves the user entered text....

    This is not the case in Safari...

  11. avatar
    wrote this comment on

    Yeah. I have updated the post with a color switching example and added your onblur technique. That color switchin and page reloading thing needs to be tested in detail...

  12. avatar
    wrote this comment on

    Thank Nicolas-

    After looking at your code I notice you had put the this.style.color=’#000′ in a different spot then you had mentioned before....

    It's all working good now-
    Now if only I could get the progressive upload status bar working... Any ideas?

  13. avatar
    wrote this comment on

    oh thats great, thanks so much. i've just found i had been looking for :)

  14. avatar
    wrote this comment on

    Thanks for these javascript tips Nicolas, they're really handy!

    I know no javascript what-so-ever despite being a bit of an expert in XHTML and CSS.
    I've decided to learn some, so this is a nice starting point, cheers!

  15. avatar
    wrote this comment on

    Hi, Great article.
    However, when this is used with a javascript validator the validation script is ignoring the fields as they are already filled in. Is there a simple fix to this?

    Cheers

  16. avatar
    wrote this comment on

    Hi Oli, I'm not sure what you mean? Can you describe it in more detail?

  17. avatar
    wrote this comment on

    thank you! (city field on my form is color changing on entry now!)

  18. avatar
    wrote this comment on

    Thanks for the tips

    Could you also post a solution for 'textarea'?

    for some reason I can't get it to work.

    Thanks

  19. avatar
    wrote this comment on

    Hello snosie, for textareas you'll need something like
    <pre>
    &lt;textarea onfocus="this.innerHTML='bar';" &gt;
    foo
    &lt;/textarea&gt;
    </pre>
    Please test it across all browsers though, it's just a quick guess.

  20. avatar
    wrote this comment on

    Big thanks Bro :)

  21. avatar
    wrote this comment on

    Thank you Nicolas, for the clear and concise tutorial.

  22. avatar
    wrote this comment on

    It's useful for me, thanks.

  23. avatar
    wrote this comment on
    Hi, thank you on post but i have problem in IE. How to get "Restore default value if nothing is entered" in in IE without "Allow blocked content" when IE restrict script running? Do i need some more script? Thank you...
  24. avatar
    wrote this comment on
    Thanks Nick, Great article with useful advice. It's helped me a lot as I needed text inside fielkds due to limited space for teh form. Top job, Alan
  25. avatar
    wrote this comment on
    HI , I have searched many site, but not able to get this kind of explanation really super thank you for your great UI. Venkat
  26. avatar
    wrote this comment on
    hi im having problem in my color because first i want to turned it to gray then if the user wants to input something on the input box it will turn to color black but in my case it still in color gray pls help me heres the code im using
  27. avatar
    wrote this comment on
    How could you decrease li and width when you click on a searchbox like this one? The searchbox is also within li.
  28. Home
  29. Contact
  • avatar
    wrote this comment on
    Well there are various techniques to do this. You can use some effects library, simply set the css property, update the class, etc.
  • avatar
    wrote this comment on
    Thanks a ton, a nice simple tutorial.
  • avatar
    wrote this comment on
    how to apply this javascript into password textboxes ?? because password textbox does not write "Your Email" deafult text, instead it shows ******* . So, what is the solution ??
  • avatar
    wrote this comment on
    I guess the new placeholder could work for that, see http://www.whatwg.org/specs/web-apps/current-work/multipage/common-input-element-attributes.html#attr-input-placeholder
  • avatar
    wrote this comment on
    Awesome post! Thanks for explaining everything so clearly. It all worked the first time. :)
  • avatar
    wrote this comment on
    Hi guys, i have a problem i can't solve, i have two input fields in my search form that i have entred the values. when i make a search i can use both input boxes and then search it works fine. but if only use one input box then the value in the second box is till there when i submit. so the search result find nothing becuse it search for the secon input box value. so is it possible on submit that the it search only for the added text in the first input box or vice versa? warm regards Anders
  • avatar
    wrote this comment on
    I'm not really sure what you mean.
  • avatar
    wrote this comment on
    Thanks Nick, This is great It really helps me. I'm new to the world of Web but not a problem implementing your codes. Best Regards, Mark
  • avatar
    wrote this comment on
    Thanks a lot. Would it be possible to put this in a separate JS file?
  • avatar
    wrote this comment on
    Certainly, you can bind functions to events, https://developer.mozilla.org/en/docs/DOM/element.addEventListener etc.
  • avatar
    wrote this comment on
    i have apply check onblur,but when i lose focus on the particular textbox aur forget to enter data ,it does not show again that error ,for which i apply check,i don't want to use onsubmit.
  • avatar
    wrote this comment on
    Having an issue making these elements required in my form. When I mark them as required, and user does not fill them in, the form still submits with the onfocus value, since it's in the box. Is there any work around?
  • avatar
    wrote this comment on
    Thank you, very useful and easy to use. Now, after an hour, when I found out that the :focus class in css for this specific input is killing the inline script. But it's a happy end and ready to be served = )
  • avatar
    wrote this comment on
    That's.... bizarre
  • avatar
    wrote this comment on
    You could check if they are the default values before submitting the form. onsubmit or something.
  • avatar
    wrote this comment on
    Thank you very much -- Absolutely brilliant! Best explanation I've seen for this. I've put the routines into functions and called them like: onSelect="focusOn('default text',this)"... and changed the font from italic-grey to normal-black when the user inputs some text. Now to have a look at modifying it for my textarea field... :)
  • avatar
    wrote this comment on
    Here's the weirdest thing. I was about to start modifying this to work with 'textarea' tags, and... it works straight off! In Firefox, IE7 and IE8 anyway :o)
  • avatar
    wrote this comment on
    thank you :)
  • avatar
    wrote this comment on
    thank u very much for the codes
  • avatar
    wrote this comment on
    Thank you for this tutorial. I have the same problem as Anders. By 'Restore default value if nothing is entered' you say something about it. When de user dicides not to input any data, but just klicks on the button search, the value in the code (by example 'search here') is where the system will search for and nothing will be found. How can I fix this?
  • avatar
    wrote this comment on
    Well... I think that's something you should catch server-side. That being said, you can probably use an onsubmit event on the form to change the value, but I don't have the time to explain this in detail atm.
  • avatar
    wrote this comment on
    you can use css :focus element ex. input:focus{color:black;}
  • avatar
    wrote this comment on
    how do I get after I input the fields of the form, the data directly to a function that I created. so after I write the data, then I press enter, automaticaly go to a function that I want. can you help me?
  • avatar
    wrote this comment on
    You might be interested in something like http://jqueryvalidation.org/ Other than that.. wait for the form to be submitted and do your stuff I guess.
  • Reply

    Cancel reply
    Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc.
    DjangoPythonBitcoinTuxDebianHTML5 badgeSaltStackUpset confused bugMoneyHackerUpset confused bugX.OrggitFirefoxWindowMakerBashIs it worth the time?i3 window managerWagtailContainerIrssiNginxSilenceUse a maskWorldInternet securityPianoFontGnuPGThunderbirdJenkinshome-assistant-logo