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);
$("#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
}
});
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
您忘记了TD标签,只需在TD之前使用open标签,最后将其关闭
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.