Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Select2's last selection?

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

like image 894
Jaeger Avatar asked Apr 25 '26 16:04

Jaeger


1 Answers

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>
like image 193
kapantzak Avatar answered Apr 28 '26 18:04

kapantzak