danyo
danyo

Reputation: 5856

jquery if siblings hasClass

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?

Upvotes: 11

Views: 24467

Answers (1)

Arun P Johny
Arun P Johny

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

Related Questions