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
You can use the :selected selector to select them, then get the .length, like this:
var count = $("#mySelect :selected").length; 3 Comments
Svante Svenson
First is better, since
$("#mySelect").val() is null if no option is selected.Nick Craver
@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.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
Nick Craver
.count() isn't a jQuery function :) .size() is, but it's just a wrapper for .length, might as well use it directly.var n = $("input:checked").length; see this for more detail: http://api.jquery.com/checked-selector/
1 Comment
Nick Craver
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.