Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check if multiple select elements (*not* a multiselect) have values?

Tags:

jquery

I have a couple of select elements:

<select id='foo1'>
    <option value=''></option>
    <option value='foo'>asdf</option>
    <option value='bar'>asdfasdf</option>
</select>

<select id='foo2'>
    <option value=''></option>
    <option value='foo'>asdf</option>
    <option value='bar'>asdfasdf</option>
</select>

<select id='foo3'>
    <option value=''></option>
    <option value='foo'>asdf</option>
    <option value='bar'>asdfasdf</option>
</select>

Is there an easy way to check if each one has any value selected that is not the first empty value without using a loop or the jQuery each method? I could do it with loops, but I'd rather use a single selector.

$("[id^=foo]").val();

Sadly doesn't work. Is there any easy way to do this with jQuery in 1 line of code, or do I have to write a loop or use an .each?

like image 913
yesman Avatar asked Nov 26 '25 05:11

yesman


2 Answers

You could use that :

if($('[id^=foo] [value=""]:selected').length === 0)
    //All selects have a value

$('select').change(function(){
    if($('[id^=foo] [value=""]:selected').length === 0)
        alert('all are selected');
    else
        alert('At least one is not selected');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id='foo1'>
    <option value=''></option>
    <option value='foo'>asdf</option>
    <option value='bar'>asdfasdf</option>
</select>

<select id='foo2'>
    <option value=''></option>
    <option value='foo'>asdf</option>
    <option value='bar'>asdfasdf</option>
</select>

<select id='foo3'>
    <option value=''></option>
    <option value='foo'>asdf</option>
    <option value='bar'>asdfasdf</option>
</select>
like image 85
Karl-André Gagnon Avatar answered Nov 28 '25 23:11

Karl-André Gagnon


You could do it this way by filtering out and checking its length property.

if($('[id^=foo]').filter(function(){ return $(this).val() !== '' }).length == 3){
   // every select has a value
} else  { 
   // at least one select doesn't have a value
} 
like image 38
Amit Joki Avatar answered Nov 29 '25 01:11

Amit Joki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!