Nick Maddren Nick Maddren - 2 months ago 5
Javascript Question

Conditional Statement Only Checking One of My Elements jQuery

I have the following code that is basically a conditional statement that checks multiple conditions.

As you can see it checks the elements with a class of

.input-bravo
to see if it has a value and to see if it has a class of
is-valid
.

$('#step-1-btn').click(function() {
if($('.form-step-1 .input--bravo').val() && $('.form-step-1 .input--bravo').hasClass('is-valid') ) {
alert('This worked')
}
else {
alert('This did not work');
}
});


The issue I am having with this is that it only checks one of the elements with
.input-bravo
and then will pass even known other elements with that class don't shouldn't pass. How do I check all of these elements on my page instead of one?

Thanks, Nick

Answer

To check if all the elements have that class, and a value

var elems = $('.form-step-1 .input--bravo');

var filtered = elems.filter(function() {
    return $(this).hasClass('is-valid') && this.value !== "";
});

if ( elems.length === filtered.length ) {...
Comments