how to update data in select2 dropdown using ajax

15,383

I don't really understand your question and think it needs some clarifying - but as far as I could understand (I ran into this problem and found your question when Googleing it...)

When I first load the page I run the following JavaScript so that all of my drop-down select boxes are styled and using select2:

$('select').select2();

But as your title states, my code below works by updating the drop-down to a new set of data -where my /store/ajax_get_zones function returns HTML for the options:

$(function() {
    $('#country').on('change', function() {
        $.post("/store/ajax_get_zones", {
            country_id: $('#country').val()
        }, function(e) {
            if (e)
                $("#state").html(e).select2();
        })
    });
});

All you have to do is call .select2() on the element after you update the data.

Screen Shots

Start with the default United States:

Starting/Default United States

Then when you change the country the state drop-down changes as well (ajax updated the inner HTML of the original select while still themed to select2

Changing the country results in the changing of the state dropdown

Share:
15,383
Admin
Author by

Admin

Updated on June 14, 2022

Comments

  • Admin
    Admin almost 2 years

    I have a select2 dropdown for location.select2 data is initialised on page load.I want to update the data at regular intervals using ajax.But when I update the data of select2 the select2 dropdown becomes read only

        jQuery("#e10_2").select2({
            allowClear: true,
            minimumInputLength: 1,
            data:{ results: locationls, text: function(item) { return item.text; }},
            formatSelection: format,
            formatResult: format
        }); 
    
  • Enrique
    Enrique almost 10 years
    Walter. Would it be possible to post or add the format of the returned data that serves as input for the #state field? Thanks
  • Wallter
    Wallter almost 10 years
    It's a JSON list with state_id and state_name key value Object: {"255": "Utah", "256": "Vermont"} - the function takes the country_id and returns the associated states or zones.