1

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.

1 Answer 1

2

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));
Sign up to request clarification or add additional context in comments.

1 Comment

Aaawwww yeeeeaaah. Works like a charm, cheers buddy. One tick coming your way in 6 minutes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.