Reputation: 417
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();
Upvotes: 0
Views: 30
Reputation: 1
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
Upvotes: 1
Reputation: 34556
Change
$(this + " .required")
To
$(this).find('.required')
The first one is mistaken syntax. It effectively tries to concatenate the jQuery reference (an object) to the form element, with the string ".required".
Upvotes: 1