Search code examples
bootstrap-multiselect

how can i disable an optgroup on change in jquery bootstrap multiselect


I have two multiselect boxes, On change of the first select box I want to disable some groups of the second select box.

I am using the following code onChange function of the multiselect plugin

    $('optgroup[label=MyGroup2]').prop('disabled', true); 

I dont understand why it is not working, how can I implement it..


Solution

  • You can use the refresh method as follows. The below example demonstrates the usage where the first optgroup will be disabled by the corresponding button, however, the example can easily be adapted to your concrete case of manipulating the optgroups in the onChange option. Note that the state of the options (i.e. whether selected or not) is preserved after disabling the optgroup, so you might want to deselect the options first.

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <title>Bootstrap Example</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css" type="text/css"/>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#multiselect').multiselect();
            
            $("#multiselect-disable-optgroup1").on('click', function() {
                $('#multiselect optgroup#optgroup1').prop('disabled', true);
                $('#multiselect').multiselect('refresh');
            });
        });
    </script>
    </head>
    <body>
        <select id="multiselect" multiple="multiple">
            <optgroup label="Group 1" id="optgroup1">
                <option value="1">Option 1</option>
                <option value="2">Option 2</option>
                <option value="3">Option 3</option>
            </optgroup>
            <optgroup label="Group 2">
                <option value="4">Option 4</option>
                <option value="5">Option 5</option>
                <option value="6">Option 6</option>
            </optgroup>
        </select>
        <button id="multiselect-disable-optgroup1">Disable Group 1</button>
    </body>
    </html>