I have multiple textboxes with the same class “.input”. Each textbox has different default text: First Name, Last Name, etc…
On the focus of a particular textbox, I’d like the default text to go away, and a “.focus” class to be added to the textbox. On the blur of that textbox, I’d like the default text to return if no text has been entered by the user. I’d also like the “.focus” class to be removed unless the user has entered text.
I know how to do this for one textbox, but not multiple (without writing a function for each textbox). I’m guessing there is a way.
I’m also working with asp.NET textboxes so I had to modify the selector.
var myText
var myBox
$('input:text.input').focus(function () {
myText = $(this).val();
myBox = $(this);
//alert('focus');
}).blur(function () {
alert($(myText).val());
});
I’m pretty sure the global vars don’t retain their values by the time the blur function is called. I’ve seen this done many times on multiple sites, I just can’t figure it out.
Any help is appreciated. Thanks!
I’ve searched and come up with something close… However, when blur is called, the default text goes away even though I’ve entered in text.
$('input:text.input').focus(function () {
if (this.value == this.defaultValue) {
this.value = '';
}
if (this.value != this.defaultValue) {
this.select();
}
});
$('input:text.input').blur(function () {
$(this).removeClass("focus");
if ($.trim(this.value == '')) {
this.value = (this.defaultValue ? this.defaultValue : '');
}
});
Thanks for your help! Here is the code with some tweaks.
$('input:text.input').focus(function () {
if($(this).hasClass('focus')) { } else {
$(this)
.data('stashed-value', $(this).val()) // stash it
.addClass('focus')
.val(''); // clear the box
}
}).blur(function () {
if ($(this).val() != '') { } else {
$(this)
.val($(this).data('stashed-value')) // retrieve it
.removeClass('focus');
}
});
One way is to stash the value you want to save within the element itself, using
data():