views:

67

answers:

2

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?

+2  A: 

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.

tvanfosson
A: 

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.

bendewey
Thanks guys that worked. I was also woding sometimes that why we use var sometimes and now i understand
Mirage