Mithun Debnath Mithun Debnath - 4 months ago 5
Javascript Question

How to Represent JSON response in a table column wise

I am using the following code to receive a json as response and represent them in a table.

$(document).ready(function() {
var settings = {
"async" : true,
"crossDomain" : true,
"url" : "Parse",
"method" : "GET",
"headers" : {
"content-type" : "application/json"
},
"processData" : false
}

$.ajax(settings).done(function(jsnData) {

var obj = JSON.parse(jsnData);
for (var i = 0, len = obj.length; i < len; i++) {
var j=0;
var trd="";
trd +="<tr>";
trd+="<td>"
+ obj[i].word
trd+= " </td>";
trd+="<td>"
+ "<select class='input-small'><option value=''>"+obj[i].senses+"</option></select>";//obj[i].senses
trd+= " </td>";
trd+="</tr>";


$('#userdata tr:last').after(trd);
}

});
});
</script>


The
userdata
is the id o the table I am using to feed this json response.

The Json format is

[
{
"word": "play",
"senses": ["n1","n2","n3"]
},


{
"word": "play1",
"senses": ["m1","m2","m3"]


}
,
{
"word": "play2",
"senses": ["j1","k2","l3"]
},
{
"word": "play3",
"senses": ["x","ny","z"]
},
{
"word": "play4",
"senses": ["p","q","r"]
}
]


In my table there are two columns,One for word and one for senses,but I want the senses column as drop down.I am getting the output as follow,
enter image description here

As you can see,the Option column which I want to use to represent senses,showing the senses for the respected word in one line,e.g. for word
play
its senses are showed as
n1,n2,n3
.I want them to be shown as drop down,i.e. for for word
play
,drop down values will be
n1 n2 and n3
for word
play1
,drop down values will be
m1 m2 and m3
.

HTML code

<table id="userdata" border="2">
<tr>
<td><b>Word</b></td>
<td><b>Options</b></td>
</tr>
<tbody>

</tbody>
</table>


I tried hard but was not been able to do it in desired way.any help would be much appreciated.

Answer

use this

 + "<select class='input-small'>";
 for(var k=0; i <obj[i].senses.length;k++){
  trd+="<option value='"+obj[i].senses[k]+"'>"+obj[i].senses[k]+"</option>";
 }
trd+="</select>";
Comments