How to show/hide input value on focus?

后端 未结 7 1980
隐瞒了意图╮
隐瞒了意图╮ 2021-02-06 12:44

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条回答
  • 2021-02-06 12:57

    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" />
    
    0 讨论(0)
  • 2021-02-06 12:58

    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.

    0 讨论(0)
  • 2021-02-06 12:59

    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...'/>
    
    0 讨论(0)
  • 2021-02-06 13:01

    This always worked for me:

    <input 
        type="text" 
        value="Name:"
        name="visitors_name" 
        onblur="if(value=='') value = 'Name:'" 
        onfocus="if(value=='Name:') value = ''"
     />
    
    0 讨论(0)
  • 2021-02-06 13:17

    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.

    0 讨论(0)
  • 2021-02-06 13:19

    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.

    0 讨论(0)
提交回复
热议问题