[jquery] 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.

This question is related to jquery dynamic html-table rows

The answer is


I have never ever come across such a strange problem like this! o.O

Do you know what the problem was? $ isn't working. I tried the same code with jQuery like jQuery("#tblEntAttributes tbody").append(newRowContent); and it works like a charm!

No idea why this strange problem occurs!


As @wirey said appendTo should work, if not then you can try this:

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

("#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/


With Lodash you can create a template and you can do that following way:

    <div class="container">
        <div class="row justify-content-center">
            <div class="col-12">
                <table id="tblEntAttributes" class="table">
                    <tbody>
                        <tr>
                            <td>
                                chkboxId
                            </td>
                            <td>
                               chkboxValue
                            </td>
                            <td>
                                displayName
                            </td>
                            <td>
                               logicalName
                            </td>
                            <td>
                                dataType
                            </td>
                        </tr>
                    </tbody>
                </table>
                <button class="btn btn-primary" id="test">appendTo</button>
            </div>
        </div>
     </div>

And here goes the javascript:

        var count = 1;
        window.addEventListener('load', function () {
            var compiledRow = _.template("<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>");
            document.getElementById('test').addEventListener('click', function (e) {
                var ajaxData = { 'chkboxId': 'chkboxId-' + count, 'chkboxValue': 'chkboxValue-' + count, 'displayName': 'displayName-' + count, 'logicalName': 'logicalName-' + count, 'dataType': 'dataType-' + count };
                var tableRowData = compiledRow(ajaxData);
                $("#tblEntAttributes tbody").append(tableRowData);
                count++;
            });
        });

Here it is in jsbin


use this

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

Here is an appendTo version using the html dropdown you mentioned. It inserts another row on "change".

$('#dropdown').on( 'change', function(e) {
    $('#table').append('<tr><td>COL1</td><td>COL2</td></tr>');
});

With an example for you to play with. Best of luck!

http://jsfiddle.net/xtHaF/12/


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to dynamic

Please help me convert this script to a simple image slider Declare an empty two-dimensional array in Javascript? Compiling dynamic HTML strings from database Changing datagridview cell color dynamically What is the difference between dynamic programming and greedy approach? Dynamic variable names in Bash Dynamically Add C# Properties at Runtime How to generate a HTML page dynamically using PHP? Change UITableView height dynamically How to create own dynamic type or dynamic object in C#?

Examples related to html-table

Table column sizing DataTables: Cannot read property 'length' of undefined TypeError: a bytes-like object is required, not 'str' in python and CSV How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3? Sorting table rows according to table header column using javascript or jquery How to make background of table cell transparent How to auto adjust table td width from the content bootstrap responsive table content wrapping How to print table using Javascript?

Examples related to rows

SQL count rows in a table Converting rows into columns and columns into rows using R Delete rows containing specific strings in R How to append rows to an R data frame Excel Create Collapsible Indented Row Hierarchies Excel CSV. file with more than 1,048,576 rows of data Find which rows have different values for a given column in Teradata SQL More than 1 row in <Input type="textarea" /> Update multiple rows with different values in a single SQL query Repeat rows of a data.frame