I have to generate N X N table suppose if I give N as 5, it should create a table with 5 rows and columns. My first plan to create an HTML in a foor loop, but I believe that using jQuery templates , its possible to generate table, which is faster than the other one.Please correct me if I am wrong.
This is my script
<script type="text/javascript">
$(document).ready(function () {
//sample data
var data = [
[
{ Row: 0, Col: 0 },
{ Row: 0, Col: 1 }
],
[
{ Row: 1, Col: 0 },
{ Row: 1, Col: 1 }
]
];
$('#trTemplate').tmpl(data).appendTo('#containerTable');
$('#testArea').html(generateNNJSON(2, 2));
$('#testSection').html(data);
$('#trTemplate').tmpl(generateNNJSON(2, 2)).appendTo('#tblArena');
});
// generate JSON
function generateNNJSON(row, col) {
var JSONdata = '[';
for (i = 0; i < row; i++) {
JSONdata += '[';
for (j = 0; j < col; j++) {
JSONdata += '{ Row:' + i + ',Col:' + j + ' }';
if (!(j == col - 1))
JSONdata += ',';
}
if (!(i == row - 1))
JSONdata += '],';
else
JSONdata += ']';
}
JSONdata += ']';
return JSONdata;
}
</script>
This is my HTML
<script id="trTemplate" type="text/x-jquery-tmpl">
<tr>
{{each $data}}
<td>${Col}</td>
{{/each}}
</tr>
</script>
<table id="containerTable" border="2">
</table>
<table id="tblArena" border="2">
</table>
<div id="testArea">
</div>
<div id="testSection">
</div>
While viewing this page only $('#trTemplate').tmpl(data).appendTo('#containerTable');
is working and the data will be like this '[[{ Row:0,Col:0 },{ Row:0,Col:1 }],[{ Row:1,Col:0 },{ Row:1,Col:1 }]]'
generateNNJSON
will returns like this [object Object],[object Object][object Object],[object Object]
So only the first table is created and second is empty.
Any idea ?
The data parameter of $.tmpl()
must be an object
, you have to convert JSON string to an object:
function generateNNJSON(row, col) {
var JSONdata = '[';
for (i = 0; i < row; i++) {
JSONdata += '[';
for (j = 0; j < col; j++) {
JSONdata += '{ "Row":' + i + ',"Col":' + j + ' }';
if (!(j == col - 1))
JSONdata += ',';
}
if (!(i == row - 1))
JSONdata += '],';
else
JSONdata += ']';
}
JSONdata += ']';
return $.parseJSON(JSONdata);
}