简体   繁体   English

从文本输入中清除(并还原)默认值

[英]Clearing (and restoring) default value from text input

I have a text box which have initial value written in, i wanna that box to be clear when it is clicked(active). 我有一个文本框,其中写入了初始值,我想在单击(活动)时将其清除。

Ex: //wanna it to be clear when clicked to enter a value from user 例如://想要在单击以从用户输入值时将其清除

just write 写吧

 <input type='text' name='myText' onFocus='this.value="";'/>

UPDATED: 更新:
if you want value back if nothing is entered 如果您不输入任何内容,则希望收回价值

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

Neither of the above solutions are very good - inline events is not a good solution in this case. 上述两种解决方案都不是很好-在这种情况下,内联事件不是一个好的解决方案。 What you'll want is to use the HTML5 placeholder attribute, and with a bit of Javascript, add support for it for browsers that do not support it. 您需要使用HTML5 placeholder属性,并使用一些Javascript,为不支持该属性的浏览器添加对该属性的支持。 Your HTML will look something like this: 您的HTML将如下所示:

<input type="text" placeholder="Search" id="search" />

This will work with the current versions of Safari and Chrome. 这将适用于当前版本的Safari和Chrome。 For the other browsers, you can use this Javascript: 对于其他浏览器,可以使用以下Javascript:

// Creates a new element and check if it has the 'placeholder' property
// If it does not, then we know that the browser does not support HTML5 placeholder
if(typeof document.createElement('input').placeholder === 'undefined'){
    // Find the input element with the id "search" and get the 'placeholder' attribute
    var input = document.getElementById('search'), 
        p = input.getAttribute('placeholder');

    // Give it the placeholder value
    input.value = p;

    // Clear input on focus, then add the placeholder text 
    // back in if there's nothing there after the user changes edits the box
    input.onfocus = function(){
        if(this.value === p) this.value = '';
    }
    input.onblur = function(){
        if(!this.value) this.value = p;
    }
}

You can see a simple demo of this here: http://jsfiddle.net/RT8Bf/ 您可以在这里看到一个简单的演示: http : //jsfiddle.net/RT8Bf/

You can do this with javascript look at the onclick event. 您可以使用javascript查看onclick事件来执行此操作。 Here a small example: 这里有个小例子:

<input type="text" onclick="this.value='';" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM