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).
$('#mySelect').click(function(e) {
if ($('option:selected',this).length > 5) {
$(e.target).removeAttr('selected');
}
});
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 page
(function($) {
$.fn.maxLimitSelect = function(max) {
if (!max || !/^\d+$/.test(max)) return this;
return this.each(function() {
$(this).bind("click change keypress",{ max: max },function(event) {
var options = $('option', this);
var max = event.data.max;
var selected = $('option:selected', this);
var indexes;
if (selected.length === max) {
indexes = $.map(options, function(e, i) {
if(e.selected) return i;
});
$.data(this, "indexes", indexes);
}
else if (selected.length > max) {
indexes = $.data(this, "indexes");
options
.removeAttr('selected')
.each(function() {
var $this = $(this);
if ($.inArray($this.prevAll().length, indexes) !== -1) {
$this.attr('selected','selected');
}
});
}
});
});
}
})(jQuery);
Then to use, it's simply
$('#mySelect').maxLimitSelect(5);
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