Use jQuery to check for number of options NOT selected in a multiselect

2.5k views Asked by At

I have a multiselect that has a huge list and I'm not allowed to have an option that just says "All".

But in the background I still want to do a check to see if all are selected or not. I saw/had some snippet of code that did this before but I can't find it. What I remember it doing is checking to see if the number of options NOT selected was equal to 0, then you knew all the options were selected.

I want to do a check like this on one line if I can:

$("#my-multiselect:not(:selected)").length === 0

But $("#my-multiselect:not(:selected)").length is only returning 1 or 0 like a true or false I imagine. Am I using the :not() incorrectly? Or what else do I need to do to get an exact count?

2

There are 2 answers

2
lmgonzalves On BEST ANSWER

You are missing a space:

$("#my-multiselect :not(:selected)").length === 0

Because you want to select the options inside #my-multiselect element.

0
showdev On

It seems that you are checking the "selected" status of the <select> element. But only the <option> elements contained by the <select> element can be "selected" -- not the <select> element itself.

To count all of the unselected <option> elements within your <select> element, use:

$("select#my-multiselect option:not(:selected)").length

See my demonstration, below:

$(function() {

  var $button=$('button#calculate'),
      $output=$('p#output');
  
  $button.on('click', function() {
    var unselected = $("select#my-multiselect option:not(:selected)").length;
    $output.text(unselected + " options unselected.");
  });

});
select#my-multiselect {
  width:60px;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="my-multiselect">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
  <option value="4">Four</option>
  <option value="5">Five</option>
</select>

<button id="calculate">Calculate</button>

<p id="output"><p>