Search code examples
javascriptjquerybootstrap-multiselect

Jq Bootstrap multiselect - At least one value must be selected


I use jq bootsrtrap multiselect and I need a select where at least one value must be selected. How to do so?

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/css/bootstrap-multiselect.css">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/js/bootstrap-multiselect.min.js"></script>

<select id="select-records" multiple="multiple" class="form-control">
    <option value="0">0</option>
    <option value="50">50</option>
    <option value="500">500</option>
</select>

$('#select-records').multiselect({
  maxHeight: 400,
  buttonWidth: '100%',
  onChange: function (element, checked) {

  // ...

  }
});

Solution

  • $("#select-records").val() return array of selected values

    if($("#select-records").val().length == 0){
    alert("You must select at least one option");
    }
    

    if you want use on chage event

    $( "#select-records" ).change(function() {
    
    if($("#select-records").val().length == 0){
    alert("You must select at least one option");
    }
    });