Search code examples
javascriptjquerybootstrap-multiselect

Bootstrap Multi-Select- Unable to Enable Select When All Options are Deselected/Unchecked


I have two selects which allow multiple selection using the bootstrap select plugin- services and payment_type. What I want is when all options in services has been deselected/unchecked then payment_type becomes enabled. Note: the disabling in the code works fine, but the enabling of the field does not. Am I doing something wrong here?

Also, payment_type and services are initially disabled, however are enabled by selection of another field.

<select id="services" class="form-control" multiple="multiple" disabled>
       <option value="tire_rotation">Tire Rotation</option>
       <option value="oil_change">Oil Change</option>
       <option value="brake_check">Brake Check</option>
 </select>


 <select id="payment_type" class="form-control" multiple="multiple" disabled>
       <option value="cash">Cash</option>
       <option value="check">Check</option>
       <option value="credit_card">Credit Card</option>
       <option value="debit_card">Debit Card</option>
 </select>
$(document).ready(function() {
       $('#services').multiselect({
           buttonWidth: '375px',
           nonSelectedText: 'Select...',
           dropLeft: true,
           includeSelectAllOption: true,
           numberDisplayed: 1,
           onChange: function() {

               var servicesSelected = $("#services :selected").length;

               if ($(servicesSelected.length != 0)) {
                  $('#payment_type').multiselect('disable');
                  $('#payment_type').multiselect("deselectAll", false).multiselect("refresh");

               } 
               else {
                    $('#payment_type').multiselect('enable');
               }
           }
       });
   });

Expected Result: When all services have been unchecked then payment_type select becomes enabled.


Solution

  • This will work...

     $(document).ready(function() {
      $('#services').multiselect({
        buttonWidth: '375px',
        nonSelectedText: 'Select...',
        dropLeft: true,
        includeSelectAllOption: true,
        numberDisplayed: 1,
        onSelectAll: function(checked) {
          enableDisablePaymentType(checked);
        },
        onChange: function() {
          var servicesSelected = $("#services :selected").length > 0 ? true : false;
          enableDisablePaymentType(servicesSelected);
        }
      });
    });
    
    function enableDisablePaymentType(servicesSelected) {
      if (servicesSelected) {
        $('#payment_type').multiselect('disable');
        $('#payment_type').multiselect("deselectAll", false).multiselect("refresh");
      } else {
        $('#payment_type').multiselect('enable');
      }
    }