user2381114
user2381114

Reputation: 147

Check if all dropdowns are empty or not jQuery

I have three select elements:

            <select id="first">
                <option></option>
                <option value="a">a</option>
                <option value="b">b</option>
                <option value="c">c</option>
            </select>
            <select id="second">
                <option></option>
                <option value="d">d</option>
                <option value="e">e</option>
                <option value="f">f</option>
            </select>
            <select id="three">
                <option></option>
                <option value="g">g</option>
                <option value="h">h</option>
                <option value="i"></option>
            </select>

All three of them must either be empty (first option), or have a value.

So <option></option> <option></option> <option></option> is ok

but not <option value="a">a</option> <option></option> <option></option> kinda thing.

I've tried this, but it isn't working as it doesn't allow all three to be empty and quits on the first case

if($("#first").val() === "" || $("#second").val() === "" || $("#third").val() === ""){
    return false;
}

Any help? I would like to do this as short/nice looking as possible

Upvotes: 0

Views: 2809

Answers (3)

Eddard Stark
Eddard Stark

Reputation: 3595

var first = $("#first").val();
var second = $("#first").val();
var three = $("#first").val();
var isValid = false;

if((first.length>0 && second.length>0 && three.length>0) || (first.length==0 && second.length>== && three.length==0)){
    isValid = true;
}

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388436

You could

var $selects = $('#first, #second, #three'),
    $selected = $selects.filter(function () {
        return this.value != ''
    });
if ($selected.length != 0 && $selected.length != $selects.length) {
    return false;
}

Demo: Fiddle

Upvotes: 5

hamed
hamed

Reputation: 8033

Try this:

if($("#first").find('option').length <=1 || $("#second").find('option').length <=1 || $("#third").find('option').length <=1){
return false;
}

Upvotes: 0

Related Questions