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?
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>
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With