Create Table with Jquery - Append

Create table with jQuery - append

This line:

$('#here_table').append( '<tr><td>' + 'result' +  i + '</td></tr>' );

Appends to the div#here_table not the new table.

There are several approaches:

/* Note that the whole content variable is just a string */
var content = "<table>"
for(i=0; i<3; i++){
content += '<tr><td>' + 'result ' + i + '</td></tr>';
}
content += "</table>"

$('#here_table').append(content);

But, with the above approach it is less manageable to add styles and do stuff dynamically with <table>.

But how about this one, it does what you expect nearly great:

var table = $('<table>').addClass('foo');
for(i=0; i<3; i++){
var row = $('<tr>').addClass('bar').text('result ' + i);
table.append(row);
}

$('#here_table').append(table);

Hope this would help.

Create table using jQuery and .append

You need to create a new tr for each row, and a new td for each cell. .append() doesn't make copies, it just keeps reusing the same DOM element.

You can use a nested loop to repeat the code for the cells.

const aside = $("#tabaside");
for (var i = 0; i < filmidata.arr.length; i++) {
let tr = $("<tr>");
$(aside).append(tr);
for (let j = 0; j < 3; j++) {
$(tr).append($("<td>", {
text: "text"
}));
}
}

Adding a table row in jQuery

The approach you suggest is not guaranteed to give you the result you're looking for - what if you had a tbody for example:

<table id="myTable">
<tbody>
<tr>...</tr>
<tr>...</tr>
</tbody>
</table>

You would end up with the following:

<table id="myTable">
<tbody>
<tr>...</tr>
<tr>...</tr>
</tbody>
<tr>...</tr>
</table>

I would therefore recommend this approach instead:

$('#myTable tr:last').after('<tr>...</tr><tr>...</tr>');

You can include anything within the after() method as long as it's valid HTML, including multiple rows as per the example above.

Update: Revisiting this answer following recent activity with this question. eyelidlessness makes a good comment that there will always be a tbody in the DOM; this is true, but only if there is at least one row. If you have no rows, there will be no tbody unless you have specified one yourself.

DaRKoN_ suggests appending to the tbody rather than adding content after the last tr. This gets around the issue of having no rows, but still isn't bulletproof as you could theoretically have multiple tbody elements and the row would get added to each of them.

Weighing everything up, I'm not sure there is a single one-line solution that accounts for every single possible scenario. You will need to make sure the jQuery code tallies with your markup.

I think the safest solution is probably to ensure your table always includes at least one tbody in your markup, even if it has no rows. On this basis, you can use the following which will work however many rows you have (and also account for multiple tbody elements):

$('#myTable > tbody:last-child').append('<tr>...</tr><tr>...</tr>');

Jquery Dynamic table create?

Try my answer

$(function () {
$("#addProduct").click(function () {
var table = $('<table></table>').addClass('foo');
for (var i = 0; i < 10; i++) {
row = $('<tr></tr>');
for (var j = 0; j < 10; j++) {
var rowData = $('<td></td>').addClass('bar').text('result ' + j);
row.append(rowData);
}
table.append(row);
}

if ($('table').length) {
$("#someContainer tr:first").after(row);
}
else {
$('#someContainer').append(table);
}
});
});

Append table with jQuery after submitting form does not display

The problems in your code:

  1. You must prevent the form from submiting and refreshing the page. Use return false on the onsubmit for this. (thats the reason of the blank page after submission):
<form id="addBook" onsubmit="return false" hidden>

</form>

  1. After adding a book, you must call showLibrary() in order for it to appear in the table:
$("#addBook").on("submit",function(){

//...

//...

//rerender the library after book add
showLibrary();

})

  1. You must clear the table tbody before rerendering the library:
function showLibrary()
{
//Clear the tbody before rendering library:
$("#books tbody").html('');


//...
//...
}

Here is your original code, with these three updates:

let library=[];
let book;

function Book(title,author,number_of_pages,read){
this.title=title;
this.author=author;
this.number_of_pages=number_of_pages;
this.read=read;
}

function addBook(title,author,number_of_pages,read){
let book=new Book(title,author,number_of_pages,read);
library.push(book);
}

addBook("Hobbit1","Tolkien",130,"read");

$(document).ready(function(){

//Show form to add a new Book
$("#newBook").on("click",function(){
$("form").slideDown(500);
})

$("#addBook").on("submit",function(){
let title=$("#title").val();
let author=$("#author").val();
let number_of_pages=$("#number_of_pages").val();
let read=$("#read").val();

addBook(title,author,number_of_pages,read);

//rerender the library after book add
showLibrary();


})

//Remove rows
$(document).on("click", "#delete", function(){

$(this).closest('tr').remove();

library.splice(library.findIndex(x=>x.title==$(this).attr('class')),1);

});

function showLibrary()
{
//Clear the tbody before rendering library:
$("#books tbody").html('');

library.forEach(function (item,index){
$("#books tbody").append("<tr> <td>"+item.title+"</td> <td> "+item.author+"<td> "+item.number_of_pages+"</td> <td> "+item.read+"</td> <td> <button id=delete class="+item.title+">Delete</button> </td> </tr>");

})
}

showLibrary();

});
<!DOCTYPE html>
<html>
<head>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<link rel="stylesheet" type="text/css" href="mystyle.css">
<title>Whatever</title>
</head>
<body>

<h2>Books</h2>

<div id="books">
<table>
<thead><tr><th>Title</th><th>Author</th><th>Pages</th><th>Read</th></tr></thead>
<tbody>


</tbody>


</table>

</div>

<button id="newBook">New Book</button>
<form id="addBook" onsubmit="return false" hidden>
<label>Title:</label><br>
<input id="title" type="text" name="title"><br>
<label>Author:</label><br>
<input id="author" type="text" name="author"><br>
<label>Number of pages:</label><br>
<input id="number_of_pages" type="text" name="number_of_pages"><br>
<label>Have you read this book ?:</label><input id="read" type="checkbox" name="read"><br>
<input type="submit" value="Add Book">
</form>
</body>
</html>

To create tr & td dynamically and append to table. Onclick pass the json selected object

You can set value of row as json object i.e :{'datas': row} inside click event handler and then access this using event object .i.e : e.data.datas .

Demo Code :

function populateResult(data, resultElementId) {
$.each(data, function(i, row) {
$trs = $(`<tr><td> ${row.name} </td></tr>`).appendTo(resultElementId);
//on click pass that row as well
$trs.on('click', {
'datas': row
}, myfunction);
})

}
function myfunction(e) {
//use event object to access data
console.log('Data : ' + JSON.stringify(e.data.datas));
}

populateResult([{
"name": "s1",
}, {
"name": "s2"
}], "#myTableBody")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<table>
<tbody id="myTableBody"></tbody>
</table>

Append data to html table using JQuery

You can use .each to iterate over the array, and .append to add rows:

const data = [
{ ItemId:1, Name:'Item 1', Description:'A', Price:1, Quantity:1, Amount:1},
{ ItemId:2, Name:'Item 2', Description:'B', Price:2, Quantity:2, Amount:2}
];

$.each(data, (index, row) => {
const rowContent
= `<tr>
<td>${row.ItemId}</td>
<td>${row.Name}</td>
<td>${row.Description}</td>
<td>${row.Price}</td>
<td>${row.Quantity}</td>
<td>${row.Amount}</td>
</tr>`;
$('#tbdata').append(rowContent);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered table-hover ">
<tr class="success">
<th>Id</th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Quantity</th>
<th>Amount</th>
</tr>
<tbody id="tbdata">
</tbody>
</table>


Related Topics



Leave a reply



Submit