Jquery json parsing for select
Hallo,
I have this json:
{
"ROWCOUNT":5,
"COLUMNS":["ID","REGIONE"],
"DATA":{
"ID":[1,2,4,3,5],
"REGIONE":["Ab开发者_运维问答ruzzo","Campania","Emilia","Molise","Toscana"]
}
I want retrieve value from ID and REGIONE with jquery, to fill a select. I have tried this one:
for(var COLUMNS in data) {
jQuery.each(data[COLUMNS], function(i, row) {
alert(row)
});
}
but I don't know how to combine one ID with the REGIONE, to obtain <option value="#ID#">#REGIONE#</option>
.
Thank you.
If I understood your question correctly, you're looking for something like this:
var options = [];
for(var i in data.ID) {
var option = $('<option />');
option.val(data.ID[i]).html(data.REGIONE[i]);
options.push(option);
}
$('select').html(options);
You can do it like this:
for(var i = 0; i < data.ID.length; i++) {
var option = $('<option></option').attr('value', data.ID[i]).text(data.REGIONE[i]);
//Do something with option
}
Your JSON looks slightly incorrect, but if we assume you have this:
"DATA": {
"ID":[1,2,4,3,5],
"REGIONE":["Abruzzo","Campania","Emilia","Molise","Toscana"]
}
You can try this:
var sel = $('<select>');
$.each(DATA.ID, function(i, id) {
sel.append( $('<option>').val(id).text( DATA.REGIONE[i] ) );
})
Will 'COLUMNS' always contain those two values ('ID' and 'REGIONE'), and will those two correspond to the two values in 'DATA'? If so you could do:
var s = $('<select />');
$(x.DATA.ID).each(function(i, id){
console.log(id, x.DATA.REGIONE[i])
$(s).append($('<option />').val(id).text(x.DATA.REGIONE[i]))
});
精彩评论