How to show/hide input value on focus?

2020-05-28 23:03发布

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.

7条回答
Root(大扎)
2楼-- · 2020-05-28 23:29

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楼-- · 2020-05-28 23:32

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" />
查看更多
仙女界的扛把子
4楼-- · 2020-05-28 23:34

This always worked for me:

<input 
    type="text" 
    value="Name:"
    name="visitors_name" 
    onblur="if(value=='') value = 'Name:'" 
    onfocus="if(value=='Name:') value = ''"
 />
查看更多
何必那么认真
5楼-- · 2020-05-28 23:36

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:

And google. ;-)

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

查看更多
等我变得足够好
6楼-- · 2020-05-28 23:39

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...'/>
查看更多
你好瞎i
7楼-- · 2020-05-28 23:40

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.

查看更多
登录 后发表回答