Question

i need to append some options in select element, What i am doing wrong here,

Remember:
I am using jquery chosen plugin.

$(document).ready(function(e) {
    $("#my_select").chosen();
    get_data()

});    

function get_data() {
    $.ajax({
            url: "<?=site_url('controller/function')?>",
            success: function(result){
                result = $.parseJSON(result);
                $.each(result, function(i, v) {
                    //alert('inside')
                    $('#my_select').append("<option value='"+v.id+"'>"+v.name+"</option>");
                });
                $("#my_select").trigger("chosen:updated");       
            }
        });
}

Json response is absolutely fine,

[{"id":"2","name":"name1"},{"id":"3","name":"name2"}]

While my html is,

<select id="my_select" name="my_select" data-placeholder="Select type">
        <option value=""></option> 
</select>    
Was it helpful?

Solution

have you tried trigger("liszt:updated") ?

OTHER TIPS

try like this,first load your data and then implement chosen

$(document).ready(function(e) {
    get_data()
    $("#my_select").chosen();

});



function get_data() {
    $.ajax({
            url: "<?=site_url('controller/function')?>",
            success: function(result){
                result = $.parseJSON(result);
                $.each(result, function(i, v) {
                    //alert('inside')
                    $('#my_select').append("<option value='"+v.id+"'>"+v.name+"</option>");
                });

            }
        });
}

This seems to be working. I've removed chosen().

<?php
if (isset($_GET['getdata'])) {
    echo '[{"id":"2","name":"name1"},{"id":"3","name":"name2"}]';
    exit;
}
?>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<script>

$(document).ready(function(e) {
    get_data()
});    

function get_data() {
    $.ajax({
            url: "http://www.website.com/test.php?getdata",
            success: function(result){
                result = $.parseJSON(result);
                $.each(result, function(i, v) {
                    $('#my_select').append("<option value='"+v.id+"'>"+v.name+"</option>");
                });      
            }
        });
}

</script>

<select id="my_select" name="my_select" data-placeholder="Select type">

</select> 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top