populate html table with jquery
suppose i have table and i want to append data in the 开发者_开发技巧middle of table through jquery.
here is my table code html
<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
here i need to append tr with jQuery
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
is it possible with jquery? if so then please guide me. if i can populate then i can do like
for (var i = 0; i < data.d.length; i++) {
$("#NamesGridView").append("<tr><td>" + data.d[i].FirstName +
"</td><td>" + data.d[i].Age + "</td></tr>");
}
}
please guide thanks
Edit Based on comment:
$('#thetable tr').not(':first').not(':last').remove();
var html = '';
for(var i = 0; i < data.d.length; i++)
html += '<tr><td>' + data.d[i].FirstName +
'</td><td>' + data.d[i].Age + '</td></tr>';
$('#thetable tr').first().after(html);
Example here: JSFiddle
Below Code will populate html table with jquery.
<table id="tablefriendsname">
<tbody>
</tbody>
</table>
$.ajax({
type: "POST",
url: "/users/index/friendsnamefromids",
data: "IDS="+requests,
dataType: "json",
success: function(response){
var name = response;
//Important code starts here to populate table
var yourTableHTML = "";
jQuery.each(name, function(i,data) {
$("#tablefriendsname").append("<tr><td>" + data + "</td></tr>");
});
}
});
If you are adding the data in for loop, it would be more performant to build the string first then add it all in one call.
var newRows = "";
for (var i = 0; i < data.d.length; i++) {
newRows += "<tr><td>" + data.d[i].FirstName +
"</td><td>" + data.d[i].Age + "</td></tr>";
}
$("table tr:first").after(newRows);
$("table tr:first").after("<tr><td>row 1, cell 1</td><td>row 1, cell 2</td></tr>")
Basically use after()
or before()
use the right selector
Live Demo
Add the id NamesGridView
to the first tr
<table border="1">
<tr id="NamesGridView">
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
and change the append
to after
.
for (var i = 0; i < data.d.length; i++) {
$("#NamesGridView").after("<tr><td>" + data.d[i].FirstName + "</td><td>" + data.d[i].Age + "</td></tr>");
}
Also see my jsfiddle.
精彩评论