Grizzly
Grizzly

Reputation: 5953

Count Number of Selected Items in ListBox

I have a listbox:

<div>
  <select id="SelectBox" multiple>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </select>
</div>

This listbox is allowing for multiple selections. All I am trying to do is count the number of selected items.

Here is my jQuery:

$("#SelectBox").change(function(){
    countSelectedItems();
});

function countSelectedItems(){
    var count = $("#SelectBox:selected").length;
  alert(count);
}

I have researched this solution from this post, but it is not working. I continue to keep being alerted with 0.

Here is my JSFiddle.

Any help is appreciated.

Upvotes: 0

Views: 3181

Answers (3)

Ionut Necula
Ionut Necula

Reputation: 11480

You need to separate the pseudo element :selected from the #SelectBox. When you use :selected pseudo selector you can use it plain as it is or on a option element, not on the select directly.

$("#SelectBox").change(function() {
  countSelectedItems();
}).change();

function countSelectedItems() {
  var count = $("#SelectBox :selected").length;
  //console.log(count);
  $('#count span').text(count);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <select id="SelectBox" multiple>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </select>
  <p id='count'>The count is: <span></span></p>
</div>

Upvotes: 2

JDB
JDB

Reputation: 25855

You are counting the number of elements with the ID "SelectBox" that are selected. What you want to do is count the number of <option> elements that are children of the "SelectBox" that are selected, like so:

#SelectBox > option:selected

$(function(){

  $('#debug').text( "number of selected options: " + $('#SelectBox > option:selected').length );

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<select id="SelectBox" multiple>
<option selected>foo</option>
<option selected>bar</option>
<option>baz</option>
</select>

<div id="debug"></div>

Upvotes: 2

Exception_al
Exception_al

Reputation: 1089

You are missing a space between the selectors :)

var count = $("#SelectBox :selected").length;

Look at the selector Documentation

Upvotes: 2

Related Questions