Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding a column in html table through javascript

I'm writing a java script code that will dynamically append a column of checkbox in an already existed table in html.

My html code goes like this:

<!DOCTYPE html>
<html>
    <head>
        <style>
            table, td {
            border: 1px solid black;
            }
        </style>
        <title>PHP MyAdmin</title>
    </head>
    <body>
        <table border="1">
            <tr>
                <th>Email_id</th>
                <th>Email_content</th>
            </tr>
            <tr>
                <td>[email protected]</td>
                <td>bla bla</td>
            </tr>
            <tr>
                <td>[email protected]</td>
                <td>bla bla</td>
            </tr>
        </table>
    </body>
</html>

And the javascript code that I'm writing to add column of checkboxes to this table created in html dynamically is as follows:

tbl = document.getElementsByTagName("body")[0];
tr = tbl.getElementsByTagName("tr");

for (i = 1; i < tr.length; i++) {
    tr.appendChild(document.createElement('td'));
    var checkbox = document.createElement("INPUT");
    checkbox.type = "checkbox";
    tr.cells[2].appendChild(checkbox);
    tbl.appendChild(tr);
}

I also want to specify an on click method on these checkboxes . Thanks in advance

like image 650
akshay Avatar asked Oct 30 '25 20:10

akshay


1 Answers

Here's an answer using jQuery, since you tagged it as that, I am assuming jQuery will do.

$("#addColumn").click(function () {
	$("tr:first").append("<td>MyTitle</td>");
	$("tr:not(:first)").append("<td>Sample Element</td>");
    //$("tr:not(:first)").append("<td><input type='checkbox' />Sample Element</td>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
    <style>
        table,
        td {
            border: 1px solid black;
        }
    </style>
    <title>PHP MyAdmin</title>
</head>
<body>
    <table border="1">
        <tr>
            <th>Email_id</th>
            <th>Email_content</th>
        </tr>
        <tr>
            <td>[email protected]</td>
            <td>bla bla</td>
        </tr>
        <tr>
            <td>[email protected]</td>
            <td>bla bla</td>
        </tr>
    </table>
</body>
</html>
<button id="addColumn">Add Column</button>
like image 166
Neil Avatar answered Nov 02 '25 10:11

Neil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!