views:

58

answers:

5

How do I make the text disappear like the way some fields work here on stackoverflow once I start putting in text? I tried out the different 'on'-actions in HTML but that didn't really do what I wanted.

Thanks.

+1  A: 

You can do it with onfocus/onblur events. For example:

<input type="text" value="search" onfocus="if(this.value=='search')this.value=''"/>

If you click on this input field, the default text "search" will disappear. The onfocus event handler checks if this input field has the value of "search" and if so then clears it, in other cases (user has already typed something in) leaves everything as is.

Andris
Thanks, that's what I was looking for :)
Nisto
A: 

use the onFocus() in javascript

<input type="text" onfocus="if(this.value == 'value') { this.value = ''; }" value="value" />
PurplePilot
+2  A: 

Presumably you mean "Labels which appear inside the input".

If you want to do this in a sane, accessible, semantic way — use a <label>, if JS is available then position it under the element, and onfocus/onblur change classes around based on the value of the element.

I knocked up a simple example at http://dorward.me.uk/tmp/label-work/example.html using jQuery (all the source that isn't part of the jQuery library is embedded in the HTML of that document for easy reading).

David Dorward
A: 

jQuery would make this easy work; http://www.jsfiddle.net/TshDN/

gnome
That really isn't any easier then the non-jQuery examples previously given.
David Dorward
You don't need a 100kB library to do a *one-liner*
Andris
The goal here was to demonstrate this in jQuery as stackoverflow uses the lib and he wanted something like stackoverflow. But yes, you are both right -- 100kb is not needed for one-liner and an onfocus would be better.
gnome
+1  A: 

If you are using HTML 5 you could use the placeholder attribute.

http://dev.w3.org/html5/spec/Overview.html#the-placeholder-attribute

Peter Forss
You could even use the Modernizr JavaScript library to test for the placeholder attribute: http://www.modernizr.com/docs/#input
Ian Oxley