Search code examples
htmldrop-down-menudropdownchoice

Defining the number of options to be selected from dropdown selection html


Is there a way to limit the number of options the user can select in a multiple select html field like the one below?

<select multiple id="color" name="color" size=5>
<option>- Choose one -</option>
<option value="blu">Blue</option>
<option value="yel">Yellow</option>
<option value="bla">Black</option>
<option value="ora">Orange</option>
</select>

Say I want to 'force' the user to select exactly two out of the four options. How would I do that?


Solution

  • Count them if there are more than desired unselect the extra one or do whatever you need with the list when you have already 2 selected ( like disable it )

    Fiddle: http://jsfiddle.net/6kMWu/

    $('#color > option').on('click', function (e) {
        var selected = ($('#color > option:selected').length);
        console.log(e.target);
        if(selected > 2)
        {
            $(e.target).removeAttr('selected');
            return false;
            e.preventDefault();
        }
    });