Elio Fernandes Elio Fernandes - 1 year ago 154
jQuery Question

How to add table rows to html table using JQuery

I am new to JQuery and I am trying to append rows to an existing table.

1) What is wrong about the code?

2) How can I insert an empty row without specifying the values in the columns?

3) Is there a better way to do this? How?



$(document).ready(function () {
var tbl = $('#mytable');
appendTableRow(tbl)
});

function appendTableRow(table) {
var newrow = '';

newrow += "<tr>";
newrow += "<td>21</td>";
newrow += "<td>22</td>";
newrow += "</tr>";

table.find('tbody tr:last').append(newrow);
}

table {
border-collapse: collapse;
}

table td {
border: 1px solid black;
}

table th {
border: 1px solid black;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable">
<thead>
<th>Col1</th>
<th>Col2</th>
</thead>

<tbody>
<tr>
<td>11</td>
<td>12</td>
</tr>
</tbody>
</table>





Regards,
Elio Fernandes

Answer Source

Your code is fine. Just append to tbody.

$(document).ready(function () {			 
			 var tbl = $('#mytable');
			 appendTableRow(tbl)
		});
		
		function appendTableRow(table) {			   
			var newrow = '';

			newrow += "<tr>";
			newrow += "<td>21</td>";
			newrow += "<td>22</td>";
			newrow += "</tr>";
			 			
			$('tbody').append(newrow);     
		}
table {
		border-collapse: collapse;
	}

	table td {
		border: 1px solid black;
	}  
  
  table th {
		border: 1px solid black;
	}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable">
	  <thead>
		<th>Col1</th>
		<th>Col2</th>
	  </thead>
	  
	  <tbody>
		<tr>
		  <td>11</td>
		  <td>12</td>
		</tr>
	  </tbody>
	</table>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download