views:

60

answers:

2

I wrote this function:

jQuery(document).ready(function() {
    jQuery('input[type=text]').each( function(i) {
        thisval = jQuery(this).val();

        jQuery(this).blur( function() {
            if (jQuery(this).val() == '') {
                jQuery(this).val(thisval);
            }
        }); // end blur function
        jQuery(this).focus( function() {
            if (jQuery(this).val() == thisval) {
                jQuery(this).val('');
            };
        });// end focus function
    }); //END each function
}); // END document ready function

It's designed to get the value of an input, then if the user clicks away without entering a new value, the old value returns. This works properly with one of the inputs on the page, but not the others. However, when I remove the .blur and .focus functions and just use alert(thisval); it alerts the name of each input, so something is wrong with my function, but I can't figure out what. Any help?

+5  A: 

You need var when declaring your variable so it's not a global one being shared, like this:

var thisval = jQuery(this).val();

Also since you're dealing specifically with text inputs you can just use the .value DOM property, like this:

jQuery(function() {
  jQuery('input[type=text]').each(function(i) {
    var thisval = this.value;
    jQuery(this).blur( function() {
        if (this.value == '') this.value = thisval;
    }).focus( function() {
        if (this.value == thisval) this.value = '';
    });
  });
});
Nick Craver
+1  A: 

thisval is a global variable so it is replaced with each loop. Make it local [stick var in front of it] and it should work like magic.

You should not just keep creating jQuery(this) over and over again. That is very inefficient. jQuery(this) is expensive. You should store one copy in a variable and use the variable.

epascarello