Reputation: 101
I have a multiple selectbox with cities to a corresponded country which enable users to select multiple cities. In the form filling process, user has to select the country first, and the cities need to changed in the multiple selectbox accordingly. Here below my country select box and cities multiple SB.
<select name="country" id="country" onchange="ajax_change(this.value)">
<option value="">--Select Country--</option>
<? echo $countryList;?>
</select>
and here is the multiple selectbox
<select multiple="multiple" name="cities[]" id="cities[]" style="height:150px; width:300px;">
<option value="">-- Select City --</option>
</select>
This is the ajax code which is returning successfully the cities list.
<script type="text/javascript">
function ajax_change(val)
{
jQuery.post(
'<?=WEB_ROOT?>index.php?rt=admin/airport/ajax',
{
val:val,
type:'get_cities'
},
function(data){
$('#cities[]').val(data);
}
);
}
</script>
But $('#cities[]').val(data)
is not working. Can you please anyone help me on this.
Upvotes: 0
Views: 1841
Reputation: 2017
You want to use the $.each function to loop over the return data (I am assuming it is JSON) and then append newly created items to your list.
Give this a try:
HTML
<select id='select' />
Javascript
var data = {
'name1':'value1',
'name2':'value2'
};
$.each(data, function(key, value) {
$('#select').append($("<option/>").text(key).val(value));
});
The above in jsfiddle: jsfiddle
You also want to remove the square brackets from the ID.
Upvotes: 2
Reputation: 1911
Just use a class and remove the [] from the id tag
<select multiple="multiple" name="cities[]" class="cities" style="height:150px; width:300px;">
<option value="">-- Select City --</option>
</select>
and
<script type="text/javascript">
function ajax_change(val)
{
//alert(val);
jQuery.post('<?=WEB_ROOT?>index.php?rt=admin/airport/ajax',
{val:val,type:'get_cities'},
function(data){
$('.cities').val(data);
}
);
}
</script>
Upvotes: 1