最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check if option is selected - With multiple selects - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 2

You 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");
        }
    } 
发布评论

评论列表(0)

  1. 暂无评论