1

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>

2
  • 2
    Do not append to table row, so NOT table.find('tbody tr:last').append(newrow); , but to table body: table.find('tbody').append(newrow); . Commented Oct 2, 2017 at 11:28
  • 1
    Possible duplicate of How do you append rows to a table using jQuery? Commented Oct 2, 2017 at 11:32

2 Answers 2

0

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>

Sign up to request clarification or add additional context in comments.

Comments

0

1) Nothing is wrong, it's doing what it's written to do. Programmatically, it's working fine.

(I almost feel this is a trick question)

2) Instead of newrow += "<td>21</td>"; use newrow += "<td> </td>"; ?

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

^ These types of questions are off-topic on here.

1 Comment

This was not a trick question! If you run the code you will see that no new row was created. The two cells created were join next to the 1st row.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.