Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding rows to tbody of a table using jQuery

I am trying to add rows to the tbody of a table. But I am having issues with achieving that. Firstly, the function where everything takes place is called on change of a dropdown from a html page. I created a tr string containing all the td inside that containing the html elements, text and other stuff. But when I am trying to add that generated row to the table using:

$(newRowContent).appendTo("#tblEntAttributes tbody"); 

I am encountering an error. The name of the table is tblEntAttributes and I am trying to add it to the tbody.

Actually what's happening is jQuery is unable to get tblEntAttributes as an html element. But I can access it using documemt.getElementById("tblEntAttributes");

Is there any way I can achieve this by adding rows to the tbody of the table. Maybe a bypass or something.

Here's the entire code:

var newRowContent = "<tr><td><input type=\"checkbox\" id=\"" + chkboxId + "\" value=\"" + chkboxValue + "\"></td><td>" + displayName + "</td><td>" + logicalName + "</td><td>" + dataType + "</td><td><input type=\"checkbox\" id=\"chkAllPrimaryAttrs\" name=\"chkAllPrimaryAttrs\" value=\"chkAllPrimaryAttrs\"></td><td><input type=\"checkbox\" id=\"chkAllPrimaryAttrs\" name=\"chkAllPrimaryAttrs\" value=\"chkAllPrimaryAttrs\"></td></tr>";  $("#tblEntAttributes tbody").append(newRowContent);  

One thing I forgot to mention is the function where this code is written is actually the success callback function for a ajax call. I am able to access the table using document.getElementById("tblEntAttributes") but for some reason $(#tblEntAttributes) doesn't seem to work.

like image 785
Anupam Avatar asked Jun 01 '12 13:06

Anupam


People also ask

How do you insert new row at a certain index in a table in jQuery?

The task is to insert a new row in that table at a certain index using JQuery. Approach: Store the table column value <td> element into the variable. Then use eq() and after() method to insert the row in a table.

How do you insert 3 rows before the last row of a table?

Click in a cell above or below where you want to add a row. Under Table Tools, on the Layout tab, do one of the following: To add a row above the cell, click Insert Above in the Rows and Columns group. To add a row below the cell, click Insert Below in the Rows and Columns group.


1 Answers

("#tblEntAttributes tbody")

needs to be

$("#tblEntAttributes tbody").

You are not selecting the element with the correct syntax

Here's an example of both

$(newRowContent).appendTo($("#tblEntAttributes")); 

and

$("#tblEntAttributes tbody").append(newRowContent); 

working http://jsfiddle.net/xW4NZ/

like image 163
wirey00 Avatar answered Oct 06 '22 22:10

wirey00