I'm trying to set a default value for several inputs at once, removing that value on focus and setting it again on blur if the input is empty. To achieve that, using jQuery, I've got this code:
var settings = {
value: '',
focusColor: 'black',
blurColor: '#CCC',
value : 'test'
};
$.each($('input'), function(index, el) {
$(el).on('blur', function(ev) {
$el = $(this);
console.log('blur ' + $el.attr('value') + ' ' + $el.attr('id'));
if ($el.attr('value') == '')
$el.attr('value', settings.value).css('color', settings.blurColor);
}).on('focus', function(ev) {
console.log('focus ' + $el.attr('value') + ' ' + $el.attr('id'));
if ($el.attr('value') == settings.value)
$(this).attr('value', '').css('color', settings.focusColor);
});
$(el).trigger('blur');
});
Having this HTML:
<input id="text" type="text" />
<input id="email" type="email" />
The problem is that, if I focus on the first input and right after on the second one, the events triggered are: focus on first input, blur on first input and focus on first input again. So if I type something in the first one, then focus on the second and in the first one again, it won't remove the sample text and will remove what I typed in.
You can see the (not) working example here. Opening the JavaScript console you'll see clearly the wrong behavior.
You forgot the set $el inside the focus event.
$.each($('input'), function(index, el) {
$(el).on('blur', function(ev) {
$el = $(this);
console.log('blur ' + $el.attr('value') + ' ' + $el.attr('id'));
if ($el.attr('value') == '')
$el.attr('value', settings.value).css('color', settings.blurColor);
}).on('focus', function(ev) {
$el = $(this); // <-- should update $el
console.log('focus ' + $el.attr('value') + ' ' + $el.attr('id'));
if ($el.attr('value') == settings.value)
$(this).attr('value', '').css('color', settings.focusColor);
});
$(el).trigger('blur');
});