开发者

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

开发者 https://www.devze.com 2023-01-11 01:14 出处:网络
How to put default value to input and when user press enter it will disappear? My code that is not working:开发者_JAVA百科

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

My code that is not working:

开发者_JAVA百科
<!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>


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消