I have a HTML dinamically created table that should be filled by the user. The user can creates a new SECTION (as many as he want) and he can creates LABELS and its TRANSLATIONS. As many as he wants. Following is part of the html code:
<table>
<tr class = "section">
<td class = "sectionName">section1</td>;
<td><input type="submit" value="Update"></td>
</tr>
<tr class="lbl_trans_Wrap">
<td class="lbl">lbl_11</td>
<td class="trans"><input type="text" value="trans_11"></td>
</tr>
<tr class = "section">
<td class = "sectionName">section2</td>;
<td><input type="submit" value="Update"></td>
</tr>
<tr class="lbl_trans_Wrap">
<td class="lbl">lbl_21</td>
<td class="trans"><input type="text" value="trans_21"></td>
</tr>
<tr class="lbl_trans_Wrap">
<td class="lbl">lbl_22</td>
<td class="trans"><input type="text" value="trans_22"></td>
</tr>
...
</table>
Than I would like to create a JSON from the values filled by the user. The object should be like this one:
var lang =
{
section1:
{
lbl_11:"trans_11"
},
section2:
{
lbl_21:"trans_21",
lbl_22:"trans_22"
}
};
To generate the above JSON I am using the following javascript:
var lang ={};
var lbl="";
var trans="";
var section="";
$( "tr" ).each(function() {//Pass trough each line in the table
if($(this).hasClass( "section" )){
section = $(this).children("td.sectionName").html();//Grab all sections
//console.log(section);
}
if($(this).hasClass( "lbl_trans_Wrap" )){
lbl = $(this).children("td.lbl").html();//Grab all labels
//console.log(lbl);
trans = $(this).children("td.trans").children("input.txt_translate").val();//Grab all translation
//console.log(trans);
lang[section]={lbl:trans};
}
});
//console.log(lang);
But the JSON is not being created as expected.
There are 2 issues here:
- The lang[section]={lbl:trans} is overriding the last one. So at the end of the process we have only the last one element.
- The lbl variable is not being recognized as variable but as a string.
Looks like this:
var lang =
{
section1:
{
lbl:"trans_11"
},
section2:
{
lbl:"trans_21"
}
};
I've tried suggestions from this post and this one. But they do not use dynamically created property. I've tried to use push but it not works to objects. I could create a JSON string and then to parse it. But I would like to know how to solve this issue in another way. Any idea in how to generate this JSON dynamically ?
UPDATE:
After James's post, this is the code that works:
$( "tr" ).each(function() {//Pass trough each line in the table
if($(this).hasClass( "section" )){
section = $(this).children("td.sectionName").children("h1").html();//Grab all sections
//console.log(section);
}
if($(this).hasClass( "lbl_trans_Wrap" )){
lbl = $(this).children("td.lbl").html();//Grab all labels
//console.log(lbl);
trans = $(this).children("td.trans").children("input.txt_translate").val();//Grab all translation
//console.log(trans);
if (!lang[section]) {
lang[section] = {};
}
lang[section][lbl] = trans;
}
});
//console.log(lang);