Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery if siblings hasClass

Tags:

jquery

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">&nbsp;</div>
    <div class="valid" style="display:none;">&nbsp;</div>
    <div class="error" style="display:none;">&nbsp;</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?

like image 905
danyo Avatar asked May 10 '13 10:05

danyo


People also ask

What does siblings do in jQuery?

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.

How can I get next sibling in jQuery?

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.

What are Javascript siblings?

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).

Is jQuery a class?

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".


1 Answers

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();
    }
});
like image 74
Arun P Johny Avatar answered Sep 27 '22 18:09

Arun P Johny