I have multiple selects at one page. I need to check them all, and check if an option is selected.
So basically I need some jquery/js that does: If every select has a option selected then ... else ...
Right now I have"
if($('.container select').val()){
//Do stuff
} else {
// Do something else
}
The problem is: this code only checks the first select on the page and I need to check them all!
Can anybody help?
I have multiple selects at one page. I need to check them all, and check if an option is selected.
So basically I need some jquery/js that does: If every select has a option selected then ... else ...
Right now I have"
if($('.container select').val()){
//Do stuff
} else {
// Do something else
}
The problem is: this code only checks the first select on the page and I need to check them all!
Can anybody help?
Share Improve this question asked Feb 25, 2014 at 18:34 Niek95Niek95 532 silver badges8 bronze badges 1- stackoverflow./questions/10213620/… – ggdx Commented Feb 25, 2014 at 18:36
4 Answers
Reset to default 2You could use:
if(!$('.container option:selected[value=""]').length){
/* All SELECT have one option selected*/
}
else {
/* At least one SELECT has no option selected */
}
Be aware, all your options must have an attribute value defined, otherwise the content option is used as value. So for default option, use e.g:
<option value="">-- No Selection --</option>
You have to grab them all, check the their values and return based on the condition presented. You can do this in an $.each loop:
var valid = true;
$('.container select').each(function () {
//if (!$(this).children('option:selected').length) { // you can do this instead of this.value if you want.
if (!this.value) {
valid = false;
return false; // this will cause the each loop to exit, instead of continue
}
});
if (valid) {
// process valid logic
}
else {
// process invalid logic
}
In case of a multiple select box
<select name="demo[]" id="demo" multiple>
<option value="a">A</option>
<option value="b">B</option>
</select>
<script>
$('#demo').on('change', function(){
if($('#demo option:selected').length == $('#demo option').length)
{
alert('Congrats! you have selected all options');
}
else
{
alert('Nah! some options still remain unselected');
}
});
</script>
try this:
ss = document.getElementById('multiple_select_id');
for (var i=0; i<ss.options.length; i++) {
if (ss.options[i].selected) {
console.log(ss.options[i].value + " is selected");
} else {
console.log(ss.options[i].value + " is not selected");
}
}