简体   繁体   中英

Why is my jQuery plugin for removing text on focus and re-adding it on blur not working?

I would like the text in the value field of a text box to disappear when that text box gains focus, and then reappear in response to the eventual blur event - but only if the value is empty (that is, if the user hasn't entered anything after putting focus into the text box). So far, I have this:

this.each(function() {  
    obj = $(this);
    var initialText = obj.val();

    obj.focus(function () { 
        if(obj.val() === initialText)
            obj.val("");    
    });


    obj.blur(function () { 
        if(obj.val() ==="")
            obj.val(initialText);   
    });
});  

This plugin works if I have only one element in the page. If I have two elements then it doesn't work. Why would this be?

The obj variable isn't scoped to the function, it's globally scoped, so there will only be one of them -- set to the last one that the plugin is applied to. Use the var keyword to scope the variable to the anonymous function alone so that there will be one for each thing that the plugin is applied to.

You'll want to write your plugin seperate from your code implementation.

Your plugin would look something like this:

 (function($) {
    $.fn.watermark = function() {  

       return this.each(function() {         
          var obj = $(this);
          var initialText = obj.val();

          obj.focus(function () { 
            if(obj.val() === initialText)
               obj.val(""); 
          });

         obj.blur(function () { 
            if(obj.val() ==="")
                obj.val(initialText);   
         });
       });
    };
 })(jQuery);  

Then to use your plugin:

$(document).ready(function() {

    $('.watermark').watermark();

});

Additionally as tvanfosson you'll want to include the var keyword on your obj . If you don't have the var keyword on your obj declaration only the last textbox will have the watermark effect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM