简体   繁体   中英

make the initial value of an input to disappear on click and to go back on blur

I have a form which contains some inputs with an initial value. I want when someone click on some input and click off the default value will go back. and If he click on it and type something in, it won't try to erase what he put if he go back to click on it again.

this is the code I tried :

<input type="text" name="prenom" value="Prénom" onfocus="this.value = this.value=='Prénom'?'':this.value;" onblur="this.value = this.value==''?'Prénom':this.value;"/>

Isn't there any other method to do that, because this code is long.

如果您不担心较旧的浏览器,可以使用以下方法:

<input type="text" name="prenom" placeholder="Prénom"/>

Use Placeholder

<input type="text" name="prenom" placeholder="Prénom"/>

See for Support

You can apply styles to placeholder text too:-

::-webkit-input-placeholder {
   color: #000000;
}

:-moz-placeholder { /* Firefox 18- */
   color:  #000000;  
}

::-moz-placeholder {  /* Firefox 19+ */
   color:  #000000;  
}

:-ms-input-placeholder {  
   color:  #000000; 
}

Demo

There are numerous plyfills available for placeholder support in older browsers you can take a look at them.. Here is an SO post on it.

Try the code below if you are worried about older browsers:

HTML

<input id="user" type="text" placeholder="someone@example.com" /><br />
<input type="password" placeholder="Password" />

JS

(function($){
var placeholderIsSupported = ('placeholder' in document.createElement('input'));
$.fn.emulatePlaceholder = function(){
if(!placeholderIsSupported){
    this.each(function(index, element){
        var handle = $(element);
        var placeholder = handle.attr('placeholder');           
        if(handle.val() == ''){
            handle.val(placeholder);    
        }
        handle.blur(function(e){
            var handle = $(this);
            if(handle.val() == ''){
                handle.val(placeholder);
            }
        });
        handle.focus(function(e){
            var handle = $(this);
            if(handle.val() == placeholder){
                handle.val('');
            }
        });
    });
}
};
})(jQuery);

USAGE

$('input').emulatePlaceholder();

jsFiddle example .

Test the fiddle above in IE<8 to see the code actually working

您可以使用标签输入的属性占位符

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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