Search code examples
phpjqueryajaxappendjquery-ui-multiselect

How to empty select box in ajax call onchange another select box with multiselect plugin of jquery?


I am having 2 dependent dropdowns. Second one is depend on first dropdown. I am using onchange event to get data in second dropdown with ajax call.

below is my 2 dropdowns and ajax call :

first select box:

<select name="cust_type" id="cust_type"  class="cust_type" 
    onchange="getCustomersByType(this.value);" > 
    <?php echo $customer_type;?>
</select>

Second select box:

<select  name="CompanyName[]" id="CompanyName" multiple  class="customer_name" > 
</select>

ajax call :

function getCustomersByType(value)
        {
            var getCust = $('#cust_type').val();

            var customer_type = value;
                $.ajax({
                method: "GET",
                dataType: 'json',
                url:"include/ajax_files/bank_book/getdata.php?getCust="+getCust,
                    success:function(data)
                        {
                            $('#CompanyName').empty();
                            $.each(data, function(index, value) 
                                {
                                    $("#CompanyName").append('<option value="' + value.CUSTOMER_ID + '"'  +
                                    '>' + value.CUSTOMER_NAME+ '</option>');
                                    $('#CompanyName').multiselect('rebuild');
                                });
                        } 
                });


        };

my data is proper. I am able to change my second dropdown with change on first. But when i am using multiselect plugin with checkbox for multiselect second dropdown failed to change data.

Below is code for multiselect :

 $(document).ready(function(){
    $('#CompanyName').multiselect({
        columns: 1,
        placeholder: 'Select Com',
        search: true,
        selectGroup: true,
        selectAll: true,
        maxPlaceholderOpts: 0,
    });
 });

please help me with this to empty select onchange first dropdown and show data.


Solution

  • Use reload method to display the new options after populating.

    $('#CompanyName').multiSelect('reload');