CaribouCode
CaribouCode

Reputation: 14398

jQuery validation plugin - pass function as parameter

I'm writing a jQuery plugin to validate forms. The plugin works great but I want to be able to define what happens after a form validates. So I want to be able to pass a function as a parameter. That function will contain a bunch of stuff to actually submit the form. That parameter needs to be called when the validation is successful.

Plugin called within the HTML file:

<script>
  $(document).ready(function(){
    $('#cForm').shdValidate({
      success : formSubmit()
    });
  });
</script>

jQuery plugin:

(function($) {
  $.fn.shdValidate = function(options) {

    //==== SETTINGS
    var shdValidateSuccess = $.extend(options).success,
        form = this;

    //==== SUBMIT CLICK
    this.children('input[type=submit]').click(function(){
      //variables
      var shdRequired = $(form).children('.required'),
          shdValid = 0;

      //validated fields
      $(shdRequired).each(function(){
        $(this).removeClass('shdValidateAlert');
        if ($(this).val() == '' || $(this).val() == $(this).attr('placeholder')){ $(this).addClass('shdValidateAlert'); }
        else { shdValid += 1; }
      });

      //outcome
      if (shdValid == $(shdRequired).length) { 
        //THE SUCCESS PARAMETER NEEDS TO BE CALLED HERE SOMEHOW
      }
      return false;
    });

  }
}(jQuery));

As you can see, I've commented where the parameter needs to be called in the plugin. At the moment I just can't get this working.

Upvotes: 1

Views: 367

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

You need to make two changes

  $(document).ready(function(){
    $('#cForm').shdValidate({
      success : formSubmit
    });
  });

And

(function($) {
  $.fn.shdValidate = function(options) {

    //==== SETTINGS
    var shdValidateSuccess = $.extend(options).success,
        form = this;

    //==== SUBMIT CLICK
    this.children('input[type=submit]').click(function(){
      //variables
      var shdRequired = $(form).children('.required'),
          shdValid = 0;

      //validated fields
      $(shdRequired).each(function(){
        $(this).removeClass('shdValidateAlert');
        if ($(this).val() == '' || $(this).val() == $(this).attr('placeholder')){ $(this).addClass('shdValidateAlert'); }
        else { shdValid += 1; }
      });

      //outcome
      if (shdValid == $(shdRequired).length) { 
        //THE SUCCESS PARAMETER NEEDS TO BE CALLED HERE SOMEHOW
        if($.isFunction(shdValidateSuccess)){
            shdValidateSuccess(form);
        }
      }
      return false;
    });

  }
}(jQuery));

Upvotes: 2

Related Questions