How to get number of selected options using jquery?

Jquery

Jquery Problem Overview


I have a multiple selection list which have more than 5 options. But i want to restrict the selection of the options to 2 or 3 options. How to do it using jquery? How to get the count of selection options in multiple selection list? I am using jquery validation plugin.

Jquery Solutions


Solution 1 - Jquery

You can use the :selected selector to select them, then get the .length, like this:

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

Solution 2 - Jquery

You can get the number of selected items in the multiselect with the following:

$('#selectList :selected').length

Where #selectList is the id of your

Solution 3 - Jquery

var n = $("input:checked").length; see this for more detail: http://api.jquery.com/checked-selector/

Solution 4 - Jquery

For checkboxes I'm using:

$('input[name="InputName"]:checked').size()

Solution 5 - Jquery

I use select2 for multi select and this worked with me

 $("#selectedItems").val().length;

note that 'selectedItems' is the id of multiselect list

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser405398View Question on Stackoverflow
Solution 1 - JqueryNick CraverView Answer on Stackoverflow
Solution 2 - JqueryhalfdanView Answer on Stackoverflow
Solution 3 - JqueryPrashant LakhlaniView Answer on Stackoverflow
Solution 4 - JqueryStrabekView Answer on Stackoverflow
Solution 5 - JqueryAhmed khaledView Answer on Stackoverflow