danny danny - 1 month ago 7
jQuery Question

Forms all inputs access in jquery plugin

I am trying to make jquery plugin for form validation (for learning). In this form i am unable to get all form fields which has class name "required". The code is following:

(function( $ ) {

$.fn.kValidation = function() {

this.on("submit", function (event ) {

event.preventDefault();

$(this + " .required").each( function () {

\\this loop dont get all form inputs which has class "required"

alert();
})

}( jQuery ));


HTML is following:

<form id="fo">
<input class="required" data-kvLimit="min:5 max:200" data-kvType="numeric" /><br>
<input class="required" data-kvLimit="min:5 max:200" data-kvType="string" /><br>
<input class="required" data-kvType="email" /><br>
<input type="submit" value="Submit" />
</form>


I am calling plugin this way

$("form").kValidation();

Answer

You can set context parameter of jQuery() to this : form element. Note also, missing closing }) at .on(), and closing } at $.fn.kValidation

  $(function() {
    (function($) {
      $.fn.kValidation = function() {
        this.on("submit", function(event) {
          event.preventDefault();
          $(" .required", this).each(function() {
            console.log(this)
          })
        })
      }
    }(jQuery));

    $("form").kValidation();

  });

plnkr http://plnkr.co/edit/DqX44H5p9HEA3P5tfZMC?p=preview

Comments