I have a jQuery script below that clears the value of an input on focus and puts it back on blur if the input remains empty. It works great, but here’s the problem:
Let’s say I have 3 input fields on the same page. I click on the first one with the value “Name”, defaultValue variable becomes “Name” and the field clears. If I click out, the value goes back to “Name”. Now if I click on the second field without refreshing the page, it clears just fine, but when I click outside, instead of getting the value “Initials”, it gets the value of the first field.
So how can I get the defaultValue variable to update itself every time I click on a field?
var adaugaInput = $('form#adauga input:text');
adaugaInput.focus(function() {
var defaultValue = $(this).val();
if($(this).attr("value") == defaultValue) $(this).attr("value", "");
adaugaInput.blur(function() {
if($(this).attr("value") == "") $(this).attr("value", defaultValue);
});
});
The explanation for why your code works the way it does is kind-of complicated. For every input field, you’re establishing (and re-establishing, on every “focus” event!) handlers for “blur” events on all the inputs. It’s confusing and hard to think about, so I’ll just sum it up and say “don’t do it that way.”
Note that I use “.val()” to get/set the “value” attribute of the input fields. Also, the “blur” handler is set up outside the “focus” handler. This code uses the jQuery “.data()” mechanism to keep the per-element default value. Not tested but it’s probably pretty close.
With a mechanism like this, it’s sometimes nice to re-style the input so that (for example) the default value shows up with a lighter font color. To do that, you’d remove and add a class to the input field, and affect the style with CSS. (The inputs would have to start off with the class; or I suppose you could apply the class on focus.)