Reputation: 3852
I am getting json data from my php code something like this :
{2: "Robert ", 3: "Adem"}
Now i want to show it in dropdown list using jQuery I'm using the following code but 'm getting object in dropdown.
jQuery(response).each(function (index, value) {
jQuery("#name").append(jQuery("<option>").val(value).text(value));
});
Upvotes: 0
Views: 119
Reputation: 11622
Aside from doing JSON.parse()
. .each()
callback should be applied on Array
not an Object
, just convert your response object to Array
using Object.values()
, here is a working snippet:
let responseStr = {2:"Robert ", 3:"Adem"}; // <----- Make sure that its an object if its not then you have to do JSON.pares().
console.log(Object.values(responseStr));
jQuery(Object.values(responseStr)).each(function(index,value){
jQuery('#name').append(jQuery('<option>').val(value).text(value));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="name"></select>
Upvotes: 1
Reputation: 684
If the response coming from your PHP file is a JSON string then you will have to convert it into a javascript array then iterate it to get your option
use JSON.parse()
;
var options = JSON.parse(JSON.stringify(response));
jQuery.each( options, function( index, value ) {
$('#name').append('<option value="'+index+'">'+value+'</option>');
});
Upvotes: 0
Reputation: 45134
you need to parse them using $.parseJSON() and to retrieve data.
If you want to do without parsing refer below.
How to access JSON Object name/value?
Upvotes: 0