Reputation: 367
I'm currently using inline javascript to clear an input text's default value on focus. If the user does not enter anything, the default value is shown once blurred. Code as follows:
onfocus="if(this.value==this.defaultValue) this.value='';" onblur="if(this.value=='') this.value=this.defaultValue;"
The problem lies in the fact that I have to add this snippet to every single text input throughout the site. What would the jQuery equivalent of this be that would automatically do this for every text input (:text).
I have concocted the following with two errors. (1) It clears any value that the text field may have. I only want it to clear it if the value is the default attr value. (2) The blur function does not insert the default value. I'm missing something incredibly simple I'm quite sure.
$(':text').focus(function() {
var value = $(this).val();
var defval = $(this).attr('value');
if(value == defval) {
$(this).val('');
}
});
$(':text').blur(function() {
var value = $(this).val();
var defval = $(this).attr('value');
if(value == '') {
$(this).val(defval);
}
});
Thanks in advance!
Upvotes: 1
Views: 3117
Reputation: 8814
I recommend using html5 placeholder instead of defaultValue, and letting modern browsers handle this, only falling back to JS in case of no placeholder support.
Anyway, this is a simple implementation using defaultValue:
$('input[type="text"]').on({
focus: function(){
var $this = $(this);
if($this.val() === $this[0].defaultValue) $this.val('');
},
blur: function(){
var $this = $(this);
if($this.val() === '') $this.val($this[0].defaultValue);
}
});
Plus, I highly recommend using a plugin, as it handles all this and some possible corner cases...
Take a look:
http://unwrongest.com/projects/defaultvalue/
Upvotes: 2