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?
The siblings() is an inbuilt method in jQuery which is used to find all siblings elements of the selected element. The siblings are those having same parent element in DOM Tree.
jQuery next() Method The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.
Siblings are nodes with the same parent (in the same childNodes list). Element Siblings are elements with the same parent (in the same children list).
jQuery hasClass() MethodThe hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".
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();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With