I am getting jsonString object in my ajax call.can any one tell me how to print this object as a dropdown .
[
{
"id" : 3272,
"name" : "a"
},
{
"id" : 3255,
"name" : "b"
},
{
"id"
: 3257,
"name" : "c"
},
{
"id" : 3253,
"name" : "d"
},
{
"id" : 3256,
"name" : "e"
}
]
That's my code:
<script>
$(document).ready(function() {
$("#customerDetails").change(function() {
var value = $('#customerDetails :selected').text();
$.ajax({
type: 'GET',
url: 'environments',
data: {
selectedcustomername: value
},
success: function(result) { //this result is my jsonstring object alert("success");
}
});
});
});
</script>
Let say myJson is
{
"myJson": [
{
"id": 3272,
"name": "a"
},
{
"id": 3255,
"name": "b"
},
{
"id": 3257,
"name": "c"
},
{
"id": 3253,
"name": "d"
},
{
"id": 3256,
"name": "e"
}
]
}
var options = eval(myJson);
Using jQuery to fill options
var length = options.length;
for(var j = 0; j < length; j++)
{
var newOption = $('<option/>');
newOption.attr('text', options[j].name);
newOption.attr('value', options[j].id);
$('#mySelect').append(newOption);
}
Also have a look here
var row=[{"id":3272,"name":"a"},{"id":3255,"name":"b"},{"id" :3257,"name":"c"},{"id":3253,"name":"d" },{"id":3256,"name":"e"}]; var select="<select id='x'>"; for(var i=0,l=row.length;i<l;i++){ var item=row[i]; select+="<option value='"+item.id+"'>"+item.name+"</option>"; } select+="</select>"; document.write(select);
By using simple for loop you can read each value and make a select box
var v = { "myJson": [ { "id": 3272, "name": "a" }, { "id": 3255, "name": "b" }, { "id": 3257, "name": "c" }, { "id": 3253, "name": "d" }, { "id": 3256, "name": "e" } ] } // in your ajax success block write this and v is your response return by ajax var str ='<select>'; for(var i=0;i<v.myJson.length;i++){ str += '<option value="'+v.myJson[i].id+'">'+v.myJson[i].name+'</option>'; } str +='</select>'; $("body").html(str)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <body></body>
Here's a working fiddle: https://jsfiddle.net/q1ekcf6z/
var returnData = [{"id":3272,"name":"a"},{"id":3255,"name":"b"},{"id"
:3257,"name":"c"},{"id":3253,"name":"d"
},{"id":3256,"name":"e"}];
var options = '';
returnData.forEach(function(data){
options+= getOption(data.name);
});
var fullDropdown = '<select>' + options + '</select>';
document.write(fullDropdown);
function getOption(textTo){
return '<option>' + textTo + '</option>';
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.