How to show/hide input value on focus?

2020-05-28 22:46发布

问题:

I see this all over the web, but was wondering if anyone has the JavaScript code for the EASIEST way to show input value on blur, but hide in on focus.

回答1:

This always worked for me:

<input 
    type="text" 
    value="Name:"
    name="visitors_name" 
    onblur="if(value=='') value = 'Name:'" 
    onfocus="if(value=='Name:') value = ''"
 />


回答2:

Since this still comes up on google, I'd like to point out that with HTML 5 you can use the placeholder attribute with an input to achieve this in one piece of html.

<input type="text" id="myinput" placeholder="search..." />

Placeholder is now standard across modern browsers, so this really would be the preferred method.



回答3:

I prefer jQuery way:

$(function(){
    /* Hide form input values on focus*/ 
    $('input:text').each(function(){
        var txtval = $(this).val();
        $(this).focus(function(){
            if($(this).val() == txtval){
                $(this).val('')
            }
        });
        $(this).blur(function(){
            if($(this).val() == ""){
                $(this).val(txtval);
            }
        });
    });
});

It is modified Hide Form Input Values On Focus With jQuery by Zack Perdue.



回答4:

The simplest approach I know of is the following:

<input 
    name="tb" 
    type="text" 
    value="some text"
    onblur="if (this.value=='') this.value = 'some text'" 
    onfocus="if (this.value=='some text') this.value = ''"  /> 


回答5:

If you don’t care about valid HTML, you use the placeholder attribute. It will work out of the box on a Safari, and you can add some unobtrusive JS to mimic this behavior in other browsers.

More reading:

  • http://www.beyondstandards.com/archives/input-placeholders/ (JS implementation)
  • http://lab.dotjay.co.uk/experiments/forms/input-placeholder-text/

And google. ;-)

The solution is similar to the one Josh Stodola posted, but it’s more flexible and universal.



回答6:

This is what I use on my blog. Just go there and check out the source code behind.

function displaySearchText(text){
    var searchField = document.getElementById('searchField');
    if(searchField != null)
        searchField.value = text;
}

Your input field should look something like this:

<input id='searchField' name='q' onblur='displaySearchText("Search...");' onfocus='displaySearchText("");' onkeydown='performSearch(e);' type='text' value='Search...'/>


回答7:

For all browsers:

<input onfocus="if(this.value == 'Your value') { this.value = '';}" onblur="if(this.value == '') { this.value = 'Your value';}" value="Your value" type="text" name="inputname" />

For newest version of browsers:

<input type="text" name="inputname" placeholder="Your value" />