Tuesday, 20 August 2013

How to Iterating through an JSON Object and append an HTML input menu/list select

How to Iterating through an JSON Object and append an HTML input menu/list
select

I've searched on here and tried several solutions offered with no luck. I
have a html input menu/list select that I want to populate with options
after the user inputs into an input text box. Once the user enters the
parameter I want javascript to call a php page and return an array/object
with the menu options.
sample of my html:
<select name="celestrials" id="celestrials" onFocus="updateCelestrials()">
<option value="Choose...">n/a</option>
</select>
my javascript in the html file(in same folder as the json.php file used in
var myURL below):
function updateCelestrials () {
var orbs = document.getElementById('systemNames').value;
var myURL =
"http://www.domain.com/folder/json.php?solarSystemName="+orbs;
$.getJSON(myURL, function(data) {
$.each(data, function() {
$("<option value='" + data + "'>" + data +
"</option>").appendTo("#celestrials");
});
});
}
my array returned by php:
echo json_encode($arrayItems, JSON_FORCE_OBJECT);
and finally my retuned array/object trimmed down for summary:
{"0":"YHN-3K I","1":"YHN-3K II","2":"YHN-3K III"}

No comments:

Post a Comment