Reputation: 1532
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?
Upvotes: 0
Views: 70
Reputation: 2123
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>
Upvotes: 1
Reputation: 1183
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();
}
});
Upvotes: 1
Reputation: 986
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
Upvotes: 1