0

If I have select in HTML like this, how would I validate this at least 2 must be selected before posting, they must select at least 2, more than 1 selected.

<select id="selection" required name="selection[]" class="multiselect form-control" multiple="multiple">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>                                                                
</select>
Aaron Magpantay
  • 405
  • 1
  • 5
  • 17
  • Possible duplicate of [Jquery form validation](https://stackoverflow.com/questions/12006344/jquery-form-validation) and/or [A simple jquery form validation script](https://stackoverflow.com/questions/15060292/a-simple-jquery-form-validation-script#answer-15072147) – Chris S. Aug 16 '18 at 12:38

3 Answers3

2

You may use the :selected selector to get the selected options, and check the length.

$('#btnSubmit').click(function() {
  if ($('#selection option:selected').length < 2) {
    console.log('Cannot submit.');
  } else {
    console.log('Can submit.');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selection" required name="selection[]" class="multiselect form-control" multiple="multiple">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>
<button id="btnSubmit">Submit</button>
Chan MT
  • 495
  • 4
  • 9
0

you can check selected options length as shown below

var len = $('#selection option[selected]').length;
if(len>=2)
  alert('valid');
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
0

In your form submit event you can add this two line of code.

if (!$("#selection option:selected").length < 2) {
    alert('Please do at least two selections');
}
Haider Ali
  • 1,081
  • 8
  • 23