javascripthtmljqueryhtml-select

How do you limit the number of options selected in an HTML <select> element?


I'm using a <select> element in a form I'm making that allows multiple selections, but I want to limit the maximum amount of selections to 10. Is this possible using JavaScript or jQuery?


Solution

  • Here is some full code for you to use:

    $(document).ready(function() {
    
      var last_valid_selection = null;
    
      $('#testbox').change(function(event) {
        if ($(this).val().length > 5) {
          alert('You can only choose 5!');
          $(this).val(last_valid_selection);
        } else {
          last_valid_selection = $(this).val();
        }
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <select multiple id="testbox" size="10">
      <option value='1'>First Option</option>
      <option value='2'>Second Option</option>
      <option value='3'>Third Option</option>
      <option value='4'>Fourth Option</option>
      <option value='5'>Fifth Option</option>
      <option value='6'>Sixth Option</option>
      <option value='7'>Seventh Option</option>
      <option value='8'>Eighth Option</option>
      <option value='9'>Ninth Option</option>
      <option value='10'>Tenth Option</option>
    </select>