Reputation: 2642
I have one table with a row. And I want to add the column to the row with the possible condition of my script with jquery. This is my sample code :
<script type="text/javascript" language="javascript">
function loadContent() {
var $parent = $("#productlist").empty(); //empty div
$parent.append('<br /><table id="myTable" cellpadding="0" cellspacing="0" width="100%" class="productlist" style="margin-left:4px; padding-top:2px;"><tbody></tbody></table>');
if (k % 3 == 0 && k == 0) {
var $table = $parent.find("#myTable > tbody");
var htmlRow = [
'<tr align="center">',
'<td align="center" id="colunm-product">',
//some data
'</td>'];
$table.append(htmlRow.join(''));
} else if ((k % 3 == 0) && (k != 0)) {
//add more <td>
} else {
//close </tr>
}
</script>
Can I create <tr>
and add more <td>
, when in the possible condition , I will append </tr>
?
Any comment please?
Upvotes: 0
Views: 2515
Reputation: 87073
var htmlRow = [];
if (k % 3 == 0 && k == 0) {
var $table = $parent.find("#myTable > tbody");
htmlRow.push(
'<tr align="center">',
'<td align="center" id="colunm-product">some data</td>');
} else if ((k % 3 == 0) && (k != 0)) {
htmlRow.push('<td align="center" id="colunm-product-2">Data 1</td>',
'<td align="center" id="colunm-product-3">Data 2</td>',
'<td align="center" id="colunm-product-2">Data 3</td>');
} else {
htmlRow.push('</tr>');
$table.append(htmlRow.join(''));
}
OR you string concatenation
var htmlRow = '';
if (k % 3 == 0 && k == 0) {
var $table = $parent.find("#myTable > tbody");
htmlRow += '<tr align="center">'+
'<td align="center" id="colunm-product">some data</td>';
} else if ((k % 3 == 0) && (k != 0)) {
htmlRow +=
'<td align="center" id="colunm-product-2">Data 1</td>'+
'<td align="center" id="colunm-product-3">Data 2</td>'+
'<td align="center" id="colunm-product-2">Data 3</td>';
} else {
htmlRow += '</tr>';
$table.append(htmlRow);
}
Upvotes: 1
Reputation: 16440
You should construct the row as a jQuery object, then append additional <td>
if required.
then finally append the row to the table.
if (k % 3 == 0) {
var $table = $parent.find("#myTable > tbody");
// htmlRow as jQuery object.
var htmlRow = $([
'<tr align="center">',
'<td align="center" id="colunm-product">',
//some data
'</td>',
'</tr>'].join('')
);
if(k != 0) {
htmlRow.append([
'<td>',
// More Data
'</td>'
].join(''));
}
// Add completed row here
$table.append(htmlRow);
}
Upvotes: 1