I have a listbox and I must limit its selection up to 5 items. If a 6th item is selected, I want to "deselect" it.
But, I'm having some problems on finding the last selected item and "deselect" it. And the last item selected it's necessary the $("#mySelect option:last")...
How can I get the selected item of a listbox??
Thanks!!!
This should do the trick:
A small re-write of Cory Larson's answer:
This will just not let the user check another option when the maximum number has been reached. And you could probably write out something to the user explaining that the maximum number has been reached.
This seems to work on a little test page I did:
This will do it, although there is a brief "flash" of selection (you might want ot have a
<span>
show up underneath the<select>
to say something like Maximum selection reached).I'll leave it as an exercise for you to get it working with keyboard selectivity too.
Here's a Working Demo
EDIT:
Ok, I'll admit that this is not the first time that I have been stung by also not testing an answer in IE too (there seem to be a lot of problems with
<select>
elements in IE), but here is a flexible solution that I have tested in IE 6 and Firefox 3.5.3 and it works in both. I've wrapped it in a plugin, in case you need this on more than one pageThen to use, it's simply
passing in the maximum number of items that can be selected. This works with key and mouse selections in both IE and Firefox versions tested although interestingly, IE 6 doesn't appear to support the Ctrl hold and Space to select multiple items, but does allow holding Shift to select a number of contiguous items. The plugin does limit this to the passed in max.
Here's a Working Demo
This will basically listen for any options that get clicked. If one gets clicked, the script checks to see how many total options are selected (including the one just clicked on). If the number of selected options is more than 5, the most-recently-clicked item will become "deselected".
If you'd like to let people know why their option just became deselected, you can do this:
Hope that works out for you. This code was inspired by peirix.
the :last part of your selector will select the "last" physical item in the select list (it doesn't relate to whether it is selected or not).
AFAIK, you need to iterate over the options, and test if each is selected (to get your count) or use the :selected pseudo selector.
UPDATE:
Wow, this was more complex than I thought!... below is a tested example that works... it could likely be cleaner, but I'll leave that to others to hack ;-)
sample HTML:
$('#mySelect option:selected').length;
doesn't seem to work on IE. Works well in Chrome though.