Reputation: 5856
I have the following jQuery which checks a form on submission:
$('#register_button').click(function (e) {
var valid = true;
$('.controls input').each(function () {
if ($(this).siblings().hasClass('error')) {
valid = false;
alert('errors!');
e.preventDefault();
return false;
}
});
});
Here is my HTML structure for an input:
<div class="controls">
<input type="text" name="register_postcode" id="register_postcode" value="<?=(isset($_REQUEST['register_postcode']) ? $_REQUEST['register_postcode'] : 'xxxxxx')?>" />
<div class="info"> </div>
<div class="valid" style="display:none;"> </div>
<div class="error" style="display:none;"> </div>
</div>
When submitting the form and there are errors the alert shows.
But when I submit the form and there are no errors, the alert still shows and the form isnt submitted.
Any ideas?
Upvotes: 11
Views: 24467
Reputation: 388446
From what I can see if the input element is valid, you are not removing the element with class error
, it is just hidden.
So change your test from being checking whether there is a sibling with class error
to whether the error
is visible
$('#register_button').click(function (e) {
var valid = true;
$('.controls input').each(function () {
if ($(this).siblings('.error:visible').length) {
valid = false;
alert('errors!');
e.preventDefault();
return false;
}
});
});
You can also do
$('#register_button').click(function (e) {
if($('.controls .error:visible').length){
alert('errors!');
e.preventDefault();
}
});
Upvotes: 16