Setting min and max number of selections in a multiple box

Viewed 1073

I'm trying to set min and max selection values for a multiple select box.

I've seen something similar done for a radio button list (only for max value) here http://jsfiddle.net/rREfg/1/

var maxCheckedCount = 5;
var maxCheckedAlertMessage = 'Woops! Too many selected!';

    jQuery('input[type=checkbox]').click(function(){
        var n = jQuery('input:checked').length;
        if(n>=maxCheckedCount){
            jQuery(this).prop('checked',false);
            alert(maxCheckedAlertMessage);
        }
    });

Now if this is my new html

<select multiple size=7>
    <option value="1">Strawberry</option>
    <option value="2">Prune</option>
    <option value="3">Lemon</option>
    <option value="4">Peach</option>
    <option value="5">Apple</option>
    <option value="6">Banana</option>
    <option value="7">Orange</option>
</select>

How can I adjust the code to get min selection 2 items and max selection 5 items?

2 Answers
Related