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.
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.
Share Improve this question asked May 13, 2013 at 20:22 CroviajoCroviajo 2491 gold badge9 silver badges19 bronze badges 1- Please specify if your running code is working so the question is about refactoring your code in a cleaner way – Vincenzo Maggio Commented May 13, 2013 at 20:26
4 Answers
Reset to default 3If you aren't worried about older browsers, you can use this:
<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="[email protected]" /><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
u can use the property placeholder of the tag input