Remove/add value onfocus/onblur if empty in jquery, input field
I know there exists many questions about this, but I dont know what to search.
I have a email field, and I want it to have "Write your email here" and when you click/do onfocus it should disap开发者_如何学运维pear. Although if you did not write something and go onblur it should appear again.
1. Markup
<input id="email" name="email" type="text" value="Write your email here" />
2. jQuery
$('#email')
.on('focus', function(){
var $this = $(this);
if($this.val() == 'Write your email here'){
$this.val('');
}
})
.on('blur', function(){
var $this = $(this);
if($this.val() == ''){
$this.val('Write your email here');
}
});
3. Demo
jQuery input placeholder
You should use HTML5 placeholder instead and use a jquery plugin for older browsers
http://diveintohtml5.ep.io/forms.html
Running example here:
http://jsfiddle.net/AamkB/
There are a lot of jquery plugins for placeholder, i used this one:
http://webcloud.se/code/jQuery-Placeholder/
You can use the inline JavaScript tags onblur / onfocus . Maybe not the most 'clean' HTML code but it certainly works in all browsers! (Didn't try IE5.5 / 6.0, but hey, who is using these oldies nowadays?! ^_^)
<input type="text" name="aSweetInputField" value="Your textfield value"
class="anyClass" onclick="if (this.defaultValue==this.value) this.value=''"
onblur="if (this.value=='') this.value=this.defaultValue">
That's it!
You do not need any JS for that. Simply use placeholder="Write your email here."
in the <input>
tag.
If you need to support IE, add http://webcloud.se/code/jQuery-Placeholder/ to make it work there, too.
<input type="text"
onfocus="if($(this).val() == 'Write your email here') $(this).val('')" onblur="if($(this).val() == '') $(this).val('Write your email here')"
value="Write your email here">
There you go.
This should work for Forms globally, just define values initially in the input's value
attribute.
<input type="text" name="example" value="example text">
<textarea name="exampleTextArea" value="example text in textarea">
var el = $('input[type=text], textarea');
el.focus(function(e) {
if (e.target.value == e.target.defaultValue)
e.target.value = '';
});
el.blur(function(e) {
if (e.target.value == '')
e.target.value = e.target.defaultValue;
});
精彩评论