user6496388
user6496388

Reputation: 49

Jquery Javascript Deselecting a select option element

I am trying to deselect the last selected option of a multiple select option element when the user has selected a certain number of values from the multiple select option. Here is my jquery code that deselects all selected option when the user tries to select the 3rd option. But i want to deselect ONLY the 3rd one.

$(document).ready(function() {
  $("select#connection_profiles").change(function() {
    if ($("select#connection_profiles option:selected").length > 2) {
      $("#connection_profiles").val([]);
      alert('You can only select a max of 2 connection profile.');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <div class="input-group"><span class="input-group-addon">Server</span>
    <select class="form-control" multiple name="connection_profiles[]" id="connection_profiles">
    <option value=''>Please select max of 2 connection profile</option>         
    <option value='10'>Rackware Cloud Server</option>
    <option value='8'>Rackspace Cloud Server</option>
    <option value='9'>Mitel MiCloud Cloud Server</option>
    <option value='7'>Carbonite Cloud Server</option>
    <option value='6'>Steam Gaming Cloud Server</option>
    <option value='5'>Microsoft Exchange Cloud Server</option>
    </select>
  </div>
</div>

Upvotes: 0

Views: 51

Answers (1)

user8761909
user8761909

Reputation:

var prevOpts = [];
$("select#connection_profiles").change(function() {
  var val = $(this).val();
  if (val.length > 2) {
    $(this).val(prevOpts);
    alert('You can only select a max of 2 connection profile.');
  } else {
    prevOpts = val;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <div class="input-group">
    <span class="input-group-addon">Server</span>
    <select class="form-control" multiple name="connection_profiles[]" id="connection_profiles">
        <option value=''>Please select max of 2 connection profile</option>
        <option value='10'>Rackware Cloud Server</option>
        <option value='8'>Rackspace Cloud Server</option>
        <option value='9'>Mitel MiCloud Cloud Server</option>
        <option value='7'>Carbonite Cloud Server</option>
        <option value='6'>Steam Gaming Cloud Server</option>
        <option value='5'>Microsoft Exchange Cloud Server</option>
    </select>
  </div>
</div>

Every time the dropdown changes, the code checks to see if its value has more than 2 elements (jQuery returns an array for multi-dropdowns). If it is, it will set the dropdown value to its previous value before you selected the 3rd element (the prevOpts variable), otherwise it will set the prevOpts variable to the selected value(s).

Upvotes: 1

Related Questions