Reputation: 45
Want to Append Select option but don't know how to fetch response values in select option.
All values fetched in response but cant append in select option, the syntax I think wrong
success: function (response) {
if (response) {
console.log(response);
$("#state").empty();
$("#state").append('<option value="" selected disabled>Select State</option>');
$.each(response, function (id, name) {
$("#state").append('<option value="' + id + '">' + name + ' </option>');
});
}
}
Console Output: The Value fetched but cant apend in select option
[{…}]
0: {id: 4, name: "Valencia"}
1: {id: 5, name: "ABC"}
length: 2
__proto__: Array(0)
Upvotes: 0
Views: 469
Reputation: 1
you have not extracting values index wise. you have an array of two json objects. so you are required to extract using index like below.
success: function (response) {
if (response) {
console.log(response);
$("#state").empty();
$("#state").append('<option value="" selected disabled>Select State</option>');
$.each(response, function (index, value) {
$("#state").append('<option value="' + response[index].id + '">' + response[index].name + ' </option>');
});
}
Upvotes: 0
Reputation: 979
success: function (response) {
if (response) {
console.log(response);
$("#state").empty();
$("#state").append('<option value="" selected disabled>Select State</option>');
$.each(response, function (index, value) {
$("#state").append('<option value="' + value.id + '">' + response[index].name + ' </option>');
});
}
The each function is implemented incorrectly, see the documentation: https://api.jquery.com/jQuery.each/
The first parameter is the index, and is optional, the second is the the current object in the loop.
I changed you code to show how to use each one
edit: missed a "."
Upvotes: 1
Reputation: 1130
.each
applied to an object returns according to manual:
jQuery.each( object, callback )
where:
object
Type: Object
The object to iterate over.
callback
Type: Function( String propertyName, Object valueOfProperty )
The function that will be executed on every value.
So inside name
you have an object.
According to this to fetch the name
property you have to use name.name
.
So, using better variable's name you can have:
$.each(response, function (id, element) {
$("#state").append('<option value="' + element.id + '">' + element.name + ' </option>');
Upvotes: 2