views:

25

answers:

2

Hi there,

to make editing of these fields easier, I'd be nice if their contents were deleted when they're clicked. Also, the default value (presented initially) needs to be submitted if it hasn't changed, this means I'm (probably) not looking for a(n HTML 5) placeholder which gets erased automatically, but actual text. Would be even better if the default value would return if the field is deselected and left blank.

Any suggestions?

Thanks a lot :-).

P.S: Example: the "your email" input at the top of http://www.makeuseof.com/.

A: 

Try it with onfocus:

<input type="text" value="Default text" onfocus="this.value = ''">
Nick
Yes I had already tried this but it didn't pop the default back in if it was left blank :-). Thanks anyway!
Chris
+2  A: 
<input type="text" value="Something" onfocus="if (this.value == this.defaultValue) this.value='';" onblur="if (this.value == '') this.value = this.defaultValue;">

If you want to use it in more than one element, you should extract the event handlers to an external function/script.

EDIT:

When using an external function, you'll need to provide a reference to the input element as a parameter to the function.

<script type="text/javascript">
    function focused(element){if (element.value == element.defaultValue) element.value='';}
    function blurred(element){if (element.value == '') element.value = element.defaultValue;}
</script>

<input type="text" value="Default Value" onfocus="focused(this)" onblur="blurred(this)">

NB: In JavaScript it is convention to have functions start with a small letter.

RoToRa
Thanks a lot for your quick response, could you explain "extracting the event handlers to an external function" in a bit more detail, I've never used javascript before (trying to learn PHP). I think I need a function rather than a script as I will be using this on only one page. Then I call the function when the input / textarea is clicked, right? Thanks once again. EDIT: Works like a charm by the way!
Chris
Got it working, great :-).
Chris