Why is my jquery.each () function not working correctly?

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 is designed to get the input value, and then, if the user presses the button without entering a new value, the old value is returned. This works correctly with one of the inputs on the page, but not with the others. However, when I remove the .blur and .focus functions and just use alert (thisval); it warns the name of each input, so something is wrong with my function, but I can’t understand that. Any help?

+3
source share
2 answers

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

jQuery () . . jQuery () . .

+1

var , , :

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

, , .value DOM, :

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 = '';
    });
  });
});
+5

Source: https://habr.com/ru/post/1766565/


All Articles