views:

89

answers:

4

Hallo,

I have this json:

{
    "ROWCOUNT":5,
    "COLUMNS":["ID","REGIONE"],
    "DATA":{
    "ID":[1,2,4,3,5],
    "REGIONE":["Abruzzo","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.

+1  A: 

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);
Tatu Ulmanen
A: 

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
}
SLaks
`data.ID[i]` is the value, not id.
Tatu Ulmanen
Fixed; thank you.
SLaks
A: 

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] ) );
})
David
A: 

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]))
});
klokop