Search code examples
jqueryjquery-pluginschainability

is it possible to maintain chainability in a jQuery plugin and also return true or false


I wrote a beginner jQuery plugin which validate a form.

this jQuery Plugin show an Error under the validating element if it left blank or if it can't pass my regular expression test.

now I want to return true or false from my plugin to disable submit button if the form has an Error.

The question is : Can I do this and also maintain Chainability of my plugin?

I have something like this:

$("input[type='text']").change(this.mytextboxvalidator(
{'regex':'something','message':'somethingelse'}));

Solution

  • When you maintain chainabilty, you return a jQuery-object. It's an object, so just add a property to this object where you store the boolean:

    (function( $ ){
    
      $.fn.someMethod = function(  ) {  
    
        var bln=true;
        return (this.each(function() {
          //modify boolean when needed
          bln=false;
        }).extend({myBoolean:bln}));
    
      };
    })( jQuery );
    

    Usage:

    if(!$('someselector').someMethod().myBoolean)
     {
      //disable the button 
     }