Reputation: 2714
I have a JSON structure which looks like this
[
{
"term_id":"28",
"name":"Audi",
"slug":"audi",
"term_group":"0"
}
]
In my HTML page, I have a dropdown button where I want to show the name after the click. To do this I have some Javascript code which looks like this:
var serviceURL = "http://www.dohamark.com/samudra/";
var make;
$('#make1').bind('pageinit', function(event) {
getEmployeeList();
});
function getEmployeeList() {
$.getJSON(serviceURL + '1st.php', function(data) {
$.each(data, function(index, employee) {
$('#make1').append('<option>' + employee.name + '</option>');
});
});
}
However, this script shows nothing in the dropdown button click but a blank place. I am very new in JavaScript and don't know much about JSON parsing. Could somebody help identify my mistake?
Upvotes: 0
Views: 2129
Reputation: 647
Please try following code :
var dd = $("#make1");
$(dd).empty();
$(dd).append($('<option />').attr('value', '-1').text('-----Select----'));
$.each(data, function(index, employee) {
dd.append($('<option />').attr('Value',employee.ID).text(employee.Name));
});
Upvotes: 0
Reputation: 7950
How about this:
for (var index in employee) {
$('#make1').append($('<option>').text(employee[index].name));
});
If I am reading your question correctly, I think that should do it.
EDIT - Just to make sure that it's clear to the OP, when I am use the variable employee
in the for in
loop, that should reference the JSON that was returned.
Upvotes: 2
Reputation: 14435
Try this:
$.each(data, function (index, employee) {
$('#make1').append('<option>' + employee.name + '</option>');
});
Fiddle: http://jsfiddle.net/KYtph/2/
Your code is fine. Make sure it's not cross domain as other have suggested and that it's parsed correctly as json.
Upvotes: 2
Reputation: 2464
I would write it like so:
$.each(data, function () {
$('#make1').append('<option>' + this.name + '</option>');
});
Also, @Mike Bryant makes a good point; if you are going cross domain, this will never work without something like JSON-P.
Upvotes: 0