Question

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?

Was it helpful?

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();
    }
});

OTHER TIPS

Possible Duplicate? HTML Multiselect Limit

you'll need an array to process the results if you want more than one option to be selected so change name to color[]

<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>

however, for your real question, i have no further information at the moment

EDIT

the answer from: HTML Multiselect Limit is:

You can use jQuery

$("select").change(function () {
      if($("select option:selected").length > 3) {
          //your code here
      }
  });

which was submitted by: infinity

This could be achieved easily with jQuery:

// Your jQuery which will limit the max selected to 2
$( document ).ready(function() {
    $(".color option").click(function(e){
        if ($(this).parent().val().length > 2) {
            $(this).removeAttr("selected");
        }
    });
});

<!-- Your HTML //-->
<select multiple id="color" name="color[]" class="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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top