views:

55

answers:

3

How to put default value to input and when user press enter it will disappear?

My code that is not working:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html>
<body>
    <input  value="default-value" type="text"/>
</body>
</html>
A: 

Don't put a default value. Just remove the value attribute.

It is not clear from your question what your goal is - however, by using a default value as you have, every time the page is loaded this value will be present.

Your page doesn't have a form element either, which is required for form submission.

Oded
can I solve that only with javascript?
Yosef
+5  A: 

When HTML5 will be supported by many browsers, it is very easy:

<input type="text" placeholder="default-value" />

Until than I would use a background image and let it disappear it a user focuses the input, as otherwise a user might submit the default value and you have to filter it out server side:

<input type="text" name="fieldname" id="fieldname" style="background-image: url("default-value.png"); background-repeat: no-repeat;" />

And the JavaScript to remove it on click (uses prototype framework):

$('fieldname').observe('click', function() {
 // if already cleared, do nothing
 if(this._cleared) return;
 this.setStyle({backgroundImage: ''});
 this._cleared = true
}); 
Kau-Boy
+4  A: 

Here is an example of a search box with the initial value 'enter search string here'. A bit of javascript clears out the box when the control gets the focus and begins typing:

<input name="txtSearch" id="txtSearch" onfocus="if (this.value=='enter search string here...') this.value = ''" value="enter search string here..." type="text"> 
EJB
The problem with this solution is that you have to write the exact same string three times. The third time would be server side to check if the input hasn't been changed.
Kau-Boy
why not just: onfocus="value=''"
Yosef
Interessting fact: SO is using your solution. But they don't have to filter "search" out, as someone might want to search for "search" :) But most of the time it is not the best solution!
Kau-Boy
@Yosef: Because this will clear the text each time a user goes back to the input field. Let's say you misspelled a word in the input and click into it again, than your text will be lost. That is really bad!
Kau-Boy