Watching multiple elements in a form, I would like to enable the submit button only when all elements successfully validate. Here’s what I have attempted:-
$('#beta_signup_form').validate({
rules: {
name: {
required: true,
minlength: 4
},
email: {
required: true,
email: true
}
},
focusCleanup: true,
onkeyup: false,
errorElement: "span",
submitHandler: function(form) {
if ($('#beta_signup_form').valid()) {
console.log("now we enable the submit button!");
}
}
});
UPDATES
I was expecting the submitHandler to be triggered and the if if ($('#beta_signup_form').valid()) condition to check that all our fields are valid, before we enable the submit button so that the user can click on it to make an ajax call to submit the form.
But somehow, nothing gets triggered when all fields are valid.
I figured out what I am getting wrong and that is the submitHandler attribute has nothing to do with detecting the “all fields validated” event. The submitHandler attribute only gets fired if I click on my form button, which is not what I need.
So my question is – which is the event I need to bind to? Is there an attribute that can be used for setting up a trigger when all fields in the form validate?
Here’s the form html code:-
<form id="beta_signup_form" postUrl="{% url 'signups_beta_users' %}" method="post" csrf_token="{{ csrf_token }}">{% csrf_token %}
<div>
<input type="text" id="name" name="name" placeholder="Name" />
</div>
<div>
<input type="email" id="email" name="email" placeholder="Email address" />
</div>
<button class="btn btn-success" type="submit" id="request-trial" href="#request-for-free-trial">Notify Me</button>
<div class="loading"></div>
</form>
My answer:
I am posting my answer in response to the previously accepted answer to demonstrate that you do not need any special function to do what the OP is asking. The
.validate()plugin already behaves like this by default.This is the jsFiddle from the accepted answer: http://jsfiddle.net/99mbLp1b/
Within that answer, the only difference is this bit of conditional code used within the
submitHandler.As per the documentation, The
submitHandleris the “Callback for handling the actual submit when the form is valid.”So if the
submitHandleris only called when the form is valid, then this whole conditional check is completely superfluous and unnecessary…It’s always going to be
true, since you’d never even get into thesubmitHandlerfunction if the form wasn’t already valid.See demo for proof: http://jsfiddle.net/uehu47w1/
As you can see, it operates identically as the jsFiddle within the other answer.