How can I use JSON data to populate the options of a select box?
I need to feed cities based on country of selection. I did it programmically but have no idea how to put JSON data into the select box. I tried several ways using jQuery, but none of them worked.
The response I am getting (I can format this differently if necessary):
["<option value='Woodland Hills'>Woodland Hills<\/option>","<option value='none'>none<\/option>","<option value='Los Angeles'>Los Angeles<\/option>","<option value='Laguna Hills'>Laguna Hills<\/option>"]
But how can I put this data as options inside a HTML <select></select>
tag?
The code I tried:
<form action="" method="post">
<input id="city" name="city" type="text" onkeyup="getResults(this.value)"/>
<input type="text" id="result" value=""/>
<select id="myselect" name="myselect" ><option selected="selected">blank</option></select>
</form>
</div>
<script>
function getResults(str) {
$.ajax({
url:'suggest.html',
type:'POST',
data: 'q=' + str,
dataType: 'json',
success: function( json ) {
$('#myselect').append(json);
}
});
};
$( '.suggest' ).keyup( function() {
getResults( $( this ).val() );
} );
</script>
I also tried to use this tutorial on auto-populating select boxes using jQuery and AJAX, but this never did anything except filling my select with "UNDEFINED" for me even though I got the response in the format the tutorial suggested.
<script type="text/javascript" charset="utf-8">
$(function(){
$("select#city").change(function(){
$.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
}
$("select#myselect").html(options);
})
})
})
</script>
Why not just make the server return the names?
["Woodland Hills", "none", "Los Angeles", "Laguna Hills"]
Then create the <option>
elements using JavaScript.
$.ajax({
url:'suggest.html',
type:'POST',
data: 'q=' + str,
dataType: 'json',
success: function( json ) {
$.each(json, function(i, value) {
$('#myselect').append($('<option>').text(value).attr('value', value));
});
}
});
Given returned json from your://site.com:
[{text:"Text1", val:"Value1"},
{text:"Text2", val:"Value2"},
{text:"Text3", val:"Value3"}]
Use this:
$.getJSON("your://site.com", function(json){
$('#select').empty();
$('#select').append($('<option>').text("Select"));
$.each(json, function(i, obj){
$('#select').append($('<option>').text(obj.text).attr('value', obj.val));
});
});
You should do it like this:
function getResults(str) {
$.ajax({
url:'suggest.html',
type:'POST',
data: 'q=' + str,
dataType: 'json',
success: function( json ) {
$.each(json, function(i, optionHtml){
$('#myselect').append(optionHtml);
});
}
});
};
Cheers