Reputation: 78
In my case I have variety of elements such as input, select, checkbox, radio. Is there any way to find out if form is valid and enable submit button. Currently what I am doing is, calling .valid() method to find form's validity which is triggering validation for elements and showing error messages as soon as I click on any element which I want to avoid.
Upvotes: 1
Views: 716
Reputation: 11502
Are you looking for such solution:
$(document).ready(function(){
$("input.submit").prop("disabled", true);
$('form').validate({
showErrors: function(errorMap, errorList) {
var formSelector = '#' + this.currentForm.id;
var formObject = $(formSelector);
var validateObject = formObject.validate();
var numberOfInvalids = validateObject.numberOfInvalids();
if(numberOfInvalids == 0)
$("input.submit").prop("disabled", false);
else
$("input.submit").prop("disabled", true);
}
});
$("#commentForm").valid();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<legend>Please provide your name, email address (won't be published) and a comment</legend>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" required>
</p>
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required>
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url">
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit" >
</p>
</fieldset>
</form>
Upvotes: 2