Reputation: 5418
So I have this jsFiddle (http://jsfiddle.net/KDAM8/), and am trying to figure out how to make the input retain it's value on the window's blur. When you focus on an input, then alt+tab out, or click on another screen, then return, it doesn't keep the correct value. Not only am I having a tough time understanding why this happens, I'm having a tough time explaining it. Hopefully you can understand what I'm asking with the jsFiddle.
<input type="text" value="name" />
<input type="password" value="password" />
$('input').each(function() {
var itemVal;
$(this).focus(function() {
itemVal = $(this).val();
$(this).val('');
});
$(this).blur(function() {
$(this).val(itemVal);
});
});
Upvotes: 0
Views: 206
Reputation: 92903
Improving on gotuskar's approach: If you cache each field's initial value in the element's .data
, you can compare it to the existing value on both focus and blur to get the desired effect:
$('input').each(function() {
$(this).data('itemVal', $(this).val());
$(this).focus(function() {
if ($(this).val() === $(this).data('itemVal')) {
$(this).val('');
}
});
$(this).blur(function() {
if (!$.trim($(this).val())) {
$(this).val($(this).data('itemVal'));
}
});
});
http://jsfiddle.net/mblase75/KDAM8/1/
Upvotes: 2
Reputation: 5516
Debug and try to understand the change I made -
$('input').each(function() {
var itemVal;
$(this).focus(function() {
itemVal = $(this).val();
if (itemVal === 'name' || itemVal === 'password') // added
$(this).val('');
});
$(this).blur(function() {
itemVal = $(this).val(); // added
if (itemVal !== 'name' || itemVal === 'password') // added
$(this).val(itemVal);
});
});
Upvotes: -1