最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Clearing (and restoring) default value from text input - Stack Overflow

programmeradmin0浏览0评论

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

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

Share Improve this question edited Nov 15, 2010 at 5:54 nikc 17k6 gold badges52 silver badges83 bronze badges asked Nov 14, 2010 at 15:46 Ahmed WaheedAhmed Waheed 1,2916 gold badges21 silver badges39 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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. Your HTML will look something like this:

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

This will work with the current versions of Safari and Chrome. For the other browsers, you can use this 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/RT8Bf/

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

You can do this with javascript look at the onclick event. Here a small example:

<input type="text" onclick="this.value='';" />
发布评论

评论列表(0)

  1. 暂无评论