I want to create a little function that blocks the user from selecting more than 3 items from a multi select list. I found some useful things on the web, which allowed me to launch an alert when the user selects more than 3 items. However, I can't find a way to remove the last selected item.
So far, here's my jQuery:
$('.metiersMission').change(function(event) {
if ($(this).val().length > 3) {
alert('Vous ne pouvez choisir que 3 métiers');
$(this).select2('val', '');
}
}});
With this code, if the user selects more than 3 items, the code simply deletes everything the user ever selected, which is obviously not what I want. I can't find anything about this anywhere, anyone has an idea?
Thank you in advance
You can listen to change event and count the selected options. If the selected options are 3, disable all other options:
$(document).on('change', 'select', function() {
var that = $(this);
var val = that.val();
if (val.length > 2) {
// Find every unselected option and disable them
that.find('option').not(':selected').attr('disabled','disabled');
} else {
// Enable all options
that.find('option').removeAttr('disabled');
}
});
select { width:250px; height:150px }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
<option value="citroen">Citroen</option>
<option value="peugeot">Peugeot</option>
</select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With