Ben
Ben

Reputation: 25807

How to put a default value into an 'input' and when user press enter it will disappear?

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">
<html>
<body>
    <input  value="default-value" type="text"/>
</body>
</html>

Upvotes: 2

Views: 509

Answers (3)

E.J. Brennan
E.J. Brennan

Reputation: 46849

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"> 

Upvotes: 4

2ndkauboy
2ndkauboy

Reputation: 9377

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
}); 

Upvotes: 7

Oded
Oded

Reputation: 498972

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.

Upvotes: 0

Related Questions