56

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.

5 Answers 5

111

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

var count = $("#mySelect :selected").length; 
Sign up to request clarification or add additional context in comments.

3 Comments

First is better, since $("#mySelect").val() is null if no option is selected.
@svinto - good catch, I override .val() to return an empty array in that case in my build, IMO it should do that by default..it's proven more useful for me, but we'll see if it ever changes.
Ya, First is better and gave correct result for my situation. Anyway thanks.
4

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

$('#selectList :selected').length 

Where #selectList is the id of your .

1 Comment

.count() isn't a jQuery function :) .size() is, but it's just a wrapper for .length, might as well use it directly.
3

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

1 Comment

I don't think this is what the OP had in mind, but more importantly it'll match every <input> including radio buttons, so be careful when using :checked alone.
1

For checkboxes I'm using:

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

Comments

0

I use select2 for multi select and this worked with me

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

note that 'selectedItems' is the id of multiselect list

Comments