Dynamically changing dropdown list with ajax

1.1k Views Asked by At

I am trying to change dropdown contents dynamically based on option choosen from another dropwdown using ajax. Even though I am able to view changed dropdown in google chrome browser inspect element or firefox inspector but on actual page there is no change in dropdown. Following is my ajax code from view file for changing dropdown based on option choosen in another dropdown.

<?php echo $output; ?>
<script>        
$(document).ready(function(){
    $("#permissions_input_box").change(function(){
        $.ajax({
            "url" : "<?php echo site_url('main/get_device_list/9'); ?>",
            "type": "POST",
            "dataType" : "json",
            "success": function(data){
                           $('select[name="firealarm"]').empty();
                           $('select[name="firealarm"]').append('<option value=""></option>');
                           $.each(data, function(key, value) {
                               $('select[name="firealarm"]').append($('<option>').text(value).attr('value', value));            
                           });
                      }
        });
    });
});
</script>

Following is short code of function get_device_list from controller

public function get_device_list($value) {
        $reponse = //Get data from database
        echo json_encode($response);
    }

The changes made in dropdown is not visible in actual page but visible when I inspect element in google chrome browser or firefox inspector. What can be the reason and how can I resolve my problem for updating dropdown on actual page with ajax?

1

There are 1 best solutions below

0
prattom On

Got the solution for my problem. With following change in ajax code it's working fine.

<?php echo $output; ?>
<script>        
$(document).ready(function(){
    $("#permissions_input_box").change(function(){
        $.ajax({
            "url" : "<?php echo site_url('main/get_device_list/9'); ?>",
            "type": "POST",
            "dataType" : "json",
            "success": function(data){
                           $('select[name="firealarm"]').empty();
                           $('select[name="firealarm"]').append('<option value=""></option>');
                           $.each(data, function(key, value) {
                               $('select[name="firealarm"]').append($('<option>').text(value).attr('value', value)).trigger("chosen:updated");            
                           });
                      }
        });
    });
});
</script>

We need to add .trigger("chosen:updated") to view the change in dropdown on actual page.