How to optimize the DOM inserting loop - javascript

For example : I want to insert many tr in a table like this
var tbody = $('#tbody')
// Suppose the articlelist is the data from ajax
while (articlelist.length > 0) {
var article = articlelist.shift(),
var tr = $(' <tr>'
+' <td>'+article.id+'</td>'
+'<td>' + article.channelid +'</td>'
+ '<td>'+article.comment+'</td>'
+'<td>'+article.last_edit_time+'</td><td>'
)
tbody.append(tr)
}
To avoid create the <tr>...</tr> in loop .Is it possible to use a class to generate the tr content ?

An optimized version:
var tbody = $('#tbody'),
htmlStr = "";
for (var i = 0, len = articlelist.length; i < len; i++) { // avoid accessing 'length' property on each iteration
htmlStr += '<tr><td>' + articlelist[i].id + '</td>'
+ '<td>' + articlelist[i].channelid + '</td>'
+ '<td>' + articlelist[i].comment + '</td>'
+ '<td>' + articlelist[i].last_edit_time + '</td><td><tr>';
}
tbody.append(htmlStr); // parses the specified text as HTML or XML and inserts the resulting nodes

You could use a loop to concatenate all the strings, then append this lengthy string all at once. This would help with performance for many trs
var tbody = $('#tbody')
var rows = ''
while (articlelist.length > 0) {
var article = articlelist.shift(),
rows += '<tr><td>'+article.id+'</td>'
+'<td>' + article.channelid +'</td>'
+ '<td>'+article.comment+'</td>'
+'<td>'+article.last_edit_time+'</td><tr>';
}
tbody.append(rows)

add a function like this to do this for you.
while (articlelist.length > 0) {
make_content(article);
}
function make_content(article) {
var tbody = $('#tbody');
var tr = $(' <tr>'
+' <td>'+article.id+'</td>'
+'<td>' + article.channelid +'</td>'
+ '<td>'+article.comment+'</td>'
+'<td>'+article.last_edit_time+'</td><td>'
)
tbody.append(tr)
}

Related

jQuery append td to dynamically created tr

I have a div with a table and I'd like to append a row with multiple td to it:
var $tblBody = $('#' + btn.attr('data-tbody-id')); //tbody of the Table
// Append the Row
$tblBody.append('<tr id="row_'+data.extra.span+'_'+data.extra.id+'_temp">');
var $tblRow = $('<tr id="row_'+data.extra.span+'_'+data.extra.id+'_temp">');
//Loop through my data and append tds
$.each(data.extra.fields, function (i, v) {
console.log(i); //Shows 0,1,2,3 etc.
$tblRow.append('' +
'<td class="' + v.cellClass + '">' +
' <span class="'+data.extra.span+'_'+v.name+'_'+data.extra.id+'">' + v.value + '</span>' +
'</td>'
)
});
Unfortunately the created to stays empty:
<tr id="row_ZWxoQXArUi82K3BjaFY4Y0x2ZWR3UT09_41_temp"></tr>
I found this: https://stackoverflow.com/a/42040692/1092632 but why is the above not working for me?
First make the tds of the row, after that append whole tr to the body.
Remove this line
$tblBody.append('<tr id="row_'+data.extra.span+'_'+data.extra.id+'_temp">');,
because you don't have a reference on it and use append part of your code after the loop.
var $tblRow = $('<tr id="row_'+data.extra.span+'_'+data.extra.id+'_temp">');
$.each(data.extra.fields, function (i, v) {
console.log(i); //Shows 0,1,2,3 etc.
$tblRow.append('' +
'<td class="' + v.cellClass + '">' +
' <span class="'+data.extra.span+'_'+v.name+'_'+data.extra.id+'">' + v.value + '</span>' +
'</td>'
)
});
$tblBody.append($tblRow); // <-----------------------
This line
var $tblRow = $('<tr id="row_'+data.extra.span+'_'+data.extra.id+'_temp">');
creates a new reference which is not in DOM yet.
instead, replace it with this
var $tblRow = $tblBody.find( "#row_' + data.extra.span + '_' + data.extra.id + '_temp">');
This will now get you the handle to the same row which has already been appended to the DOM.
Here you with one more solution using ES6 template literals
var $tblBody = $('#' + btn.attr('data-tbody-id')); //tbody of the Table
// Append the Row
var rowid = 'row_' + data.extra.span + '_' + data.extra.id + '_temp';
$tblBody.append(`<tr id=${rowid} />`);
//Loop through my data and append tds
$.each(data.extra.fields, function (i, v) {
console.log(i); //Shows 0,1,2,3 etc.
$(`#${rowid}`).append(
`<td class="${v.cellClass}">
<span class="${data.extra.span}_${v.name}_${data.extra.id}">
${v.value}
</span>
</td>`);
});
Once you appended the tr then use the id instead of get the row & appending the td.
Hope this will help you.
change the code to something like this
var $tblBody = $('#' + btn.attr('data-tbody-id')); //tbody of the Table
// Append the Row
$tblBody.append('<tr id="row_'+data.extra.span+'_'+data.extra.id+'_temp"></tr>');
var $tblRow = $('#'+'row_'+data.extra.span+'_'+data.extra.id+'_temp');
//Loop through my data and append tds
$.each(data.extra.fields, function (i, v) {
console.log(i); //Shows 0,1,2,3 etc.
$tblRow.append('' +
'<td class="' + v.cellClass + '">' +
' <span class="'+data.extra.span+'_'+v.name+'_'+data.extra.id+'">' + v.value + '</span>' +
'</td>'
)
});
You forgot to append tblRow to the tblBody. Adding the last line would fix your code
// Append the Row
$tblBody.append('<tr
id="row_'+data.extra.span+'_'+data.extra.id+'_temp">');
var $tblRow = $('<tr
id="row_'+data.extra.span+'_'+data.extra.id+'_temp">');
//Loop through my data and append tds
$.each(data.extra.fields, function (i, v) {
console.log(i); //Shows 0,1,2,3 etc.
$tblRow.append('' +
'<td class="' + v.cellClass + '">' +
' <span
class="'+data.extra.span+'_'+v.name+'_'+data.extra.id+'">' + v.value +
'</span>' +
'</td>'
)
});
$tblBody.append($tblRow);

Append button to a table row dynamically using jquery

I have an array of JavaScript JSON objects which is being parsed from a JSON formatted-string. Now what I'm doing is that I'm looping through the array and append the data to a table within the page.
jQuery Code:
$.each(objArr, function(key, value) {
var tr = $("<tr />");
$.each(value, function(k, v) {
tr.append($("<td />", {
html: v
}));
$("#dataTable").append(tr);
})
})
The code works perfectly and the table is getting populated successfully
But what I'm looking for is that, I want to add a delete button at the end of the row, by which the user will delete the row, and it also important to handle the click event in order to perform the required action
I've done this in another way, but it is not that efficient, I want to use the code above to accomplish that as it is more efficient:
for (var i = 0; i < objArr.length; i++) {
var tr = "<tr>";
var td1 = "<td>" + objArr[i]["empID"] + "</td>";
var td2 = "<td>" + objArr[i]["fname"] + "</td>";
var td3 = "<td>" + objArr[i]["lname"] + "</td>";
var td4 = "<td>" + objArr[i]["phone"] + "</td>";
var td5 = "<td>" + objArr[i]["address"] + "</td>";
var td6 = "<td >" + objArr[i]["deptID"] + "</td>";
var td7 = "<td>" + objArr[i]["email"] + "</td>";
var td8 = "<td>" + '<button id="' + objArr[i]["empID"] + '" value="' + objArr[
i]["empID"] + '" onclick="onClickDelete(' + objArr[i]["empID"] +
')">Delete</button>' + "</td></tr>";
$("#dataTable").append(tr + td1 + td2 + td3 + td4 + td5 + td6 + td7 + td8);
}
Any suggestions please?
Try something like this:
$.each(objArr, function (key, value) {
var tr = $("<tr />");
$.each(value, function (k, v) {
tr.append($("<td />", { html: v }));
tr.append("<button class='remove' />");
$("#dataTable").append(tr);
})
})
This shall append the button at the end of the tr with class remove.
Try this, I've include event handler for the each buttons inside the table.
CHANGES:
Adding Event Listener for each buttons inside the table.
Call method (function) with parameters.
Note:
I am using, fadeOut method for fading purposes only. So you can see the changes. You can change the script as your need.
EXPLAINS :
var cRow = $(this).parents('tr'); on this line we have $(this) which mean we've select the button object that you've clicked, and search the parent with tag-name tr. We need to do this because we need to take control of all data inside the tr object.
var cId = $('td:nth-child(2)', cRow).text(); has mean search second td object wich located on cRow object. And take the text from the selected td.
JQUERY REFFERENCES :
.parents()
:nth-child()
$(this) OR $(this)
$(document).ready(function() {
var jsonData = [
{id: 'A01', name: 'Fadhly'},
{id: 'A02', name: 'Permata'},
{id: 'A03', name: 'Haura'},
{id: 'A04', name: 'Aira'}
];
$.each(jsonData, function(key, val) {
var tr = '<tr>';
tr += '<td>' + (key + 1) + '</td>';
tr += '<td>' + val.id + '</td>';
tr += '<td>' + val.name + '</td>';
tr += '<td><button class="delete" data-key="'+ (key + 1) +'">Delete</button></td>';
tr += '</tr>';
$('tbody').append(tr);
});
$('button.delete').on('click', function() {
var cRow = $(this).parents('tr');
var cId = $('td:nth-child(2)', cRow).text();
var intKey = $(this).data('key');
cRow.fadeOut('slow', function() {
doDelete(cId, intKey);
});
});
function doDelete(param1, param2) {
alert('Data with\n\nID: [' + param1 + ']\nKey: [' + param2 + ']\n\nRemoved.');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" width="100%">
<thead>
<tr>
<th>#</th>
<th>Id</th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Coffeescript : For loop to concatenate HTML <td> element

Playing around a coffeescript. I have the following for loop to concat a html element in native javascript which works well. At the moment I just couldnt get the value json data i.e i.a , i.b from coffeescript.
//.js file
function createTr(json){
var tr='';
for (var i=0;i<json.data.length;i++){
var data ='<tr><td>' + json.data[i].a + ' - ' + json.data[i].b +
'</td>'+
'<td>' + json.data[i].c +
'</td>'+
'<td>' + json.data[i].d +
'</td>'+
'</tr>';
tr +=data;
}
return tr;
}
The coffescript is per below
//.coffeescript
createTr = (json) ->
tr=''
tr + '<tr><td>' + i.a + '-' + i.b+'</td> <td>'+i.c+'</td><td>'+i.d+'</td></tr>' for i in json.data
tr
the source map for the autogenerated javascript from the coffeescript as per below
//autogenerated js file from coffeescript file above
createTr = function(json) {
var i, j, len, ref, tr;
tr = '';
ref = json.data;
for (j = 0, len = ref.length; j < len; j++) {
i = ref[j];
tr + '<tr><td>' + i.a + '-' + i.b + '</td><td>' + i.c + '</td><td>' + i.d + '</td></tr>';
}
return tr;
};
The only difference is a missing assignment. The CoffeeScript version should be:
createTr = (json) ->
tr=''
tr += '<tr><td>' + i.a + '-' + i.b+'</td> <td>'+i.c+'</td><td>'+i.d+'</td></tr>' for i in json.data
tr
##.coffee file
createTr = (json) ->
tr = ''
for item in json.data
data = """<tr>
<td>#{item.a}-#{item.b}</td>
<td>#{item.c}</td>
<td>#{item.d}</td></tr> """
tr += data
return tr
And read http://coffeescript.org/ about loop, string and variables in string like "Some text #{variable}"
I prefer to use a join on the array that the for loop creates:
createTr = (json) ->
('<tr><td>' + i.a + '-' + i.b+'</td> <td>'+i.c+'</td><td>'+i.d+'</td></tr>' for i in json.data).join("")
or kind of like #yavor.makc if it was my code I might focus on readability:
createTr = (json) ->
(for i in json.data
"
<tr>
<td>#{i.a}-#{i.b}</td>
<td>#{i.c}</td>
<td>#{i.d}</td>
</tr>
"
).join("")

JS Append Row in HTML Table

I have a hidden field with some values, I have to append these values in HTML table.The number of columns in table is fixed.
I have appended successfully,but after first row,it should append data in new row,instead it is appending in the same row.
This is how I am doing
$("#btntbl").click(function () {
debugger
var tabl = $("#testTable");
var vals = $("#txthidden").val();
for (var i = 0; i < vals.split(";").length; i++) {
for (var j = 0; j < vals.split(";")[i].split(",").length; j++) {
tabl.append("<td>" + vals.split(";")[i].split(",")[j] + "</td>");
}
}
});
Also note that some users dont have value of disabled column
JS Fiddle
How can I add new row each time clicking the button?
You need to split twice and create tr for each row:
$("#btntbl").click(function () {
var tabl = $("#testTable"),
vals = $("#txthidden").val(),
rows = vals.split(';'),
columns, i;
for (i = 0; i < rows.length; i++) {
columns = rows[i].split(',');
tabl.append(
'<tr>' +
'<td>' + columns[0] + '</td>' +
'<td>' + columns[1] + '</td>' +
'<td>' + (columns[2] || '') + '</td>' +
'</tr>'
);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="btntbl" value="Export to table">
<input type="hidden" value="User1,pwd1;User2,pwd2,disabled;User3,pwd3,disabled;User4,pwd4" id="txthidden" />
<table id="testTable" border="2">
<thead valign="top">
<tr>
<th>User</th>
<th>Password</th>
<th>Disabled</th>
</tr>
</thead>
</table>
Just change target by adding a row
Change
var tabl = $("#testTable");
To
var tabl = $('<tr>');
$("#testTable").append( tab1);
Here is how you can do it
var convertToTable = function (val) {
val = val.split(';');
val = val.map(function (v) {
v = v.split(',');
if (v.length === 2) v[v.length] = 'NA';
return '<td>' + v.join('</td><td>') + '</td>';
});
val = '<tr>' + val.join('</tr><tr>') + '</tr>';
return val;
}
and then
tabl.html(convertToTable(vals));
Demo here
jsFiddle demo
$("#btntbl").click(function () {
var parts = $("#txthidden").val().split(";"), i=0;
for (;i<parts.length;) {
var j=0, tr="<tr>", subParts=parts[i++].split(",");
for (;j<3;) tr += "<td>" + (subParts[j++]||"") +"</td>"; // concatenate
$("#testTable").append( tr +"</tr>" ); // Append once
}
});
You forgot about TD tag, just use open tag before TD and close it in the end

Need help using a 'for loop' extracting data from a Table

Just wondering if anyone can help me.
I have created a table, and using Javascript I am extracting all the data and placing it into divs.
$(function () {
$('table').each(function () {
var output = "",
table = $(this),
rowHead = table.find('tbody tr th'),
rowSubject = table.find('thead tr th:not(:first-child)'),
rowContent = table.find('tbody tr td'),
copy = table.clone();
output += '<div class="mobiled-table">';
for (i = 0; i < rowHead.length; i++) {
output += '<div class="head">' + $(rowHead[i]).html() + '</div>';
for (j = 0; j < rowSubject.length; j++) {
output += '<div class="subject">' + $(rowSubject[j]).html() + '</div>';
output += '<div class="content">' + $(rowContent[i]).html() + '</div>';
}
}
output += '</div>';
$('table').append(output);
});
});
It all works great except the .content class isnt working correctly. I believe I am using the wrong 'for loop' or I need to create another 'for loop'. Please take a look at my codepen and you will see my problem
http://codepen.io/anon/pen/JrKBf
I hope someone can help.
Because rowContent contains the matrix of cells but as a one dimension array, you have to translate (i, j) to a valid index for rowContent which is (i * 4) + j:
rowContent[i]
should be replaced by:
rowContent[(i*4) + j]
In a simpler way, you can do like this,
var container=$("#container");
$("table tr:not(:first)").each(function() {
var heading = $(this).find("th").html();
container.append('<div class="subject">' + heading + '</div>');
$(this).find("td").each(function(i) {
container.append('<div class="subject">' + $("table th").eq($(this).index()).html() + '</div>');
container.append('<div class="content">' + $(this).html() + '</div>');
});
});
Fiddle

Categories