Making text in inputs disappear when you click on it

Sunday, October 19th, 2008

This is probably really REALLY obvious to other front-end coders, but I didn’t know how to do it. It’s a great way to save room on a design, but still label things clearly. So here it is….

<input onfocus=”this.value=”” type=”text” value=”sometext” />

So you can put an id or class on this as you normally would, but the words ’sometext’ will appear until someone clicks on the input box. If you want them to have to select and delete the text before they enter in their own text….

<input onfocus=”this.select()” type=”text” value=”sometext” />

Update: My good friend Andrew, of Pepsmedia, has informed me that this is a bit naughty, as I’m putting a javascript function on an actual html element. He suggests going to this link and using the jquery method.

http://docs.jquery.com/Events/focus#fn



6 comments

  1. Ewan says:

    I knew about this.select(), but the first one is even better. Have just applied to 4 or 5 search boxes. Thanks!

  2. Dan says:

    Well you’ve successfully wierded me out. This was one of the things on my “get this fixed” list for a client project and low and behold, you blog the solution.

    Thanks :)

  3. kat says:

    Wow! I’m glad you guys found this stuff as useful as me! Will update post with some of the javascript stuff when I figure it out :)

  4. Luc says:

    I’ve got a jQuery function that makes this particular problem very very easy – all you have to do is add this after your document.ready() and change the #id :
    http://www.project14.co.uk/hosted/jquery-dissapear.txt (I wasn’t sure if the comments would mangle the script or not)

  5. Andrew P says:

    Hi Luc, I prefer to not use the defaultValue as it allows for the corner case of the person wanting to type in the same value in a field as the default without affecting the clearing behavior. By attaching a class, and using this to define if the field has been used, it also allows for styling to be applied.

  6. Luc says:

    @Andrew P – that’s certainly another way round the problem – I try to be descriptive in the fields though, and thus far no-one has a username/email of “Your email address”. I use another function for validation/styling….

Leave a Reply

(will not be published)