by Mikael Henriksson
22. July 2010 20:33
I wanted to clear some textboxes when it gets focus so that the user does not have to clear the textbox before they enter whatever text. I came up with the following pretty quickly. $('input[type=text]').focus(function () {
$(this).val('');
});
This worked like a charm!
I clicked a textbox and it got cleared, perfect right? Wrong! The problem here is that no matter how the textbox gets focus the box will be cleared. While tabbing through the form I cleared it completely and had to reload the entire page to get the values back. I thought of implementing some sort of ctrl+z to undo changes but realized I am better of not going down that road.
If it isn't broken…
UPDATE (2010-07-26): As suggested in the comments it’s actually a great idea to store the value locally and if the textbox is empty when the user leaves it we just add the original value back. This can be done like follows:
$(document).ready(function() {
$('input[type=text]').bind('focusin', function(e) {
tbData = $(this).val();
$(this).val('')
});
$('input[type=text]').bind('focusout', function(e) {
if ($(this).val() == '') {
$(this).val(tbData);
}
});
});
I’d like to shorten this a little but can’t get it working as expected. I’d probably want to get rid of the global variable for instance. Expect another update sometime soon.
UPDATE (2010-08-05): I found another way of solving the exact same problem which sort of makes more sense even though I can’t get rid of the global parameter.
$('input[type=text]').live('focusin focusout', function (evt) {
if (evt.type == 'focusin') {
tbData = $(this).val();
$(this).val('');
} else {
if ($(this).val() == '') {
$(this).val(tbData);
}
}
});
0f9391a0-2742-4e5b-a473-5d4ec1990e10|0|.0
Tags: jQuery
jQuery