1

Can anyone show me how to go about making this jQuery plugin chainable? The plugin limits text input into a field, and returns a remaining text count to the 2nd argument if passed in. Thanks.

(function($) {

$.fn.extend({
    limit: function(limit, element) {
        var interval;
        var self=$(this);
        $(this).focus(function(){
            interval = window.setInterval(function(){
                substring(self, limit, element);
            },100)
        });
        $(this).blur(function(){
            clearInterval(interval);
            substring(self, limit, element);
        });
        substring(self, limit, element);
    }
});

function substring(self, limit, element) {
    var val = $(self).val();
    var length = val ? val.length : 0 ;
    if( length > limit ) {
        $(self).val($(self).val().substring(0,limit));
    }
    var toe = typeof element;
    if (toe!='undefined') {
        if (toe=='string') {
            $(element).html((limit-length<=0)?'0':limit-length);
        } else if (toe=='object') {
            element.html((limit-length<=0)?'0':limit-length);
        }
    }
}

})(jQuery);
Rich Bradshaw
  • 71,795
  • 44
  • 182
  • 241
regan
  • 305
  • 2
  • 15

3 Answers3

5

Just return this; at the end of the method.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

Always return this at the end of a plugin method (which is also the expected behaviour and should always be done unless there is a good and well documented reason):

$.fn.extend({
    limit: function(limit, element) {
        var interval;
        var self=$(this);
        $(this).focus(function(){
            interval = window.setInterval(function(){
                substring(self, limit, element);
            },100)
        });
        $(this).blur(function(){
            clearInterval(interval);
            substring(self, limit, element);
        });
        substring(self, limit, element);
        return this;
    }
});
Daff
  • 43,734
  • 9
  • 106
  • 120
2

I would go a step further and allow this to work on an array of jQuery elements by using the each() function:

$.fn.extend({
    limit: function(limit, element) {
        return this.each(function() {
            var self=$(this);
            $(this).focus(function(){
                interval = window.setInterval(function(){
                    substring(self, limit, element);
                },100)
            });
            $(this).blur(function(){
                clearInterval(interval);
                substring(self, limit, element);
            });
            substring(self, limit, element);
        });
    }
});

Also see http://docs.jquery.com/Plugins/Authoring#Maintaining_Chainability for more information regarding the authoring of jQuery plugins.

nav
  • 3,035
  • 1
  • 20
  • 24