javascript - How to get Select2 to update a ajax call when country value is changed -
i can't seem find easy example of how update states list when country list has changed. examples i've seen using sorts of bits , peices work depending on version , giving solution.
can me how can done without ugly hacks. i've tried far , whilst works, if change drop down second time, new values appended old ones instead of replacing them. i've tried destroying , rebuilding old values remain.
the data coming server valid json id , text values. far i've had no luck in getting state list update new country state values when country changed
<select id="country" name="country" class="form-control" data-placeholder="select..."> <optgroup label="country"> <option></option> <option value="us" > united states</option> <option value="au" > austrailia</option> </optgroup> </select> <select id="state" name="state" class="form-control" data-placeholder="select..."> <optgroup label="state"> <option></option> </optgroup> </select> $("#country").select2().on("change", function(e) { var country = e.val; $.post("states", { country_id: country }, function(e) { if (e) $("#states").select2({ data: e }); }) }); $("#state").select2();
these values sent server
[{ id: 'alb', text: 'alabama' }, { id: 'als', text: 'alaska' }, { id: 'ari', text: 'arizona' }]
you have remove <option>
tags select before setting new data:
$.post("states", { country_id: country }, function(e) { if (e){ $("#states option").remove(); $("#states").select2({ data: e }); } })
you may want refine example avoid removing placeholders, if any.
see jsfiddle: https://jsfiddle.net/drj84go5/
Comments
Post a Comment