Trying to make two chained auto populating select fields using select2 plugin The first select contains countries names(static select) and the second shows the states of the country selected from the first select my code is
<select id="country" name="country" size="1" class=" form-control">
<option></option>
<option value="1">USA</option>
<option value="2">Untied Kingdom</option>
<option value="3">France</option>
etc........
</select>
<select id="states" name="states" size="1" class="form-control">
<option></option>
</select>
The JavaScript Code
$(document).ready(function() {
$('#country').select2({
placeholder: 'Select Country',
allowClear: true
});
$('#state').select2({
placeholder: 'Select State',
allowClear: true
});
$('#country').change(function() {
var selectedCountries = $('#countryoption:selected').val();
var selectedCountries = 'id='+ selectedCountries;
$.ajax({
type: 'POST',
url: 'http://localhost/CodeIgniter/countries/get_state/',
dataType: 'html',
data: selectedCountries,
}).done( function( data ) {
data = $.map(data, function(item) {
return { id: item.id, text: item.name };
});
$('#state').select2({
data: data
});
}
})
});
});
The Returened Results in JSON
{"id":"1","text":"Chigaco"}{"id":"4","text":"Albama"}{"id":"2","text":"Tulsa"} etc...........
I searched a lot for an example to help me with this but nothing working right all I need is to show the states of the country chosen in the first select and pass it to the second select known that I'm using select2 v4.0 and jquery v2