I’m just starting to get my hands dirty with some basic jQuery. I want to be able to add a “defaultValue” attribute to any textbox and then have the box cleared on focus and then the default value reinserted into the textbox if the value is blank. I’ve come up with a basic couple of function to do this, but is there a better way? I seem to recall seeing some examples of jQuery functions that don’t rely on two separate methods…
$(document).ready(function () {
$('input[type=text]').click(function () {
var defaultValue = $(this).attr('defaultValue');
if ($(this).val() == defaultValue)
$(this).val('');
});
$('input[type=text]').blur(function () {
var defaultValue = $(this).attr('defaultValue');
if ($(this).val() == '')
$(this).val(defaultValue);
});
});
Use the
$(function() { });shortcut for.ready()Use
.focus()instead of.click()Only select
$('input[type=text]')from the DOM once. You can chain method calls against a jQuery object.Don’t use
.val()to get thevalueanddefaultValueof atextinput. They are accessible directly from the element’s property name with full cross-browser compatibility.If you wanted, you could shorten the selector from
'input[type=text]'to'input:text'EDIT: Removed a stray
).Also, based on @jAndy’s suggestion, the expression in the
if()statement of theblurevent has been changed to test for strings that have only space characters. I used the unary[using] jQuery’s+operator to do this. An alternative as suggested by jAndy would be to use$.trim()method.If you want a single function for both events, you could do this:
EDIT: Changed it to use
$.trim()as @jAndy originally suggested, since the+will give an improper result when the input is"0", or like" 0 ".