tags:

views:

49

answers:

3

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.

Thanks in Advance.

+2  A: 

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

lakhlaniprashant.blogspot.com
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.
Nick Craver
+4  A: 

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

var count = $("#mySelect :selected").length;
Nick Craver
First is better, since `$("#mySelect").val()` is null if no option is selected.
svinto
@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.
Nick Craver
Ya, First is better and gave correct result for my situation. Anyway thanks.
NooBDevelopeR
A: 

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

$('#selectList :selected').length

Where #selectList is the id of your .

halfdan
`.count()` isn't a jQuery function :) `.size()` is, but it's just a wrapper for `.length`, might as well use it directly.
Nick Craver
@Nick, thanks. You're totally right..
halfdan