简体   繁体   中英

How to create checkbox column in the table?

I am dynamically creating a table using JavaScript code below:

function CreatTable(data) {

    var tablearea;
    var table;
    var thead;
    var tr;
    var th;

    tablearea = document.getElementById('ShowDataID');
    table = document.createElement('table');
    thead = document.createElement('thead');
    tr = document.createElement('tr');

    for (var i = 0; i < data.length; i++) {
        var headerTxt = document.createTextNode(data[i]);
        th = document.createElement('th');
        th.appendChild(headerTxt);
        tr.appendChild(th);
        thead.appendChild(tr);
    }

    table.appendChild(thead);

    for (var i = 1; i < 4; i++) {
        tr = document.createElement('tr');
        tr.appendChild(document.createElement('td'));
        tr.appendChild(document.createElement('td'));
        tr.appendChild(document.createElement('td'));
        tr.cells[0].appendChild(document.createTextNode('John'));
        tr.cells[1].appendChild(document.createTextNode('McDowell'));
        tr.cells[2].appendChild(document.createTextNode('ddd@gmail.com'));

        table.appendChild(tr);
    }
    tablearea.appendChild(table);
}
</script>

When I create table I also need to create checkbox column in the table above.

Any idea how I can implement it using JavaScript? Or related link?

I'm not sure if this is what you're asking:

var checkbox = document.createElement("INPUT");
checkbox.type = "checkbox";

and then you'd append checkbox to each row in order to form a new column.

See this fiddle: http://jsfiddle.net/qeeu18g1/3/ I added comments where I added things.

(is this a duplicate of this question ?)

Use the following JS code:

var x = document.createElement("INPUT");
x.setAttribute("type", "checkbox");
x.setAttribute("name", "city");
x.setAttribute("value", "London");
x.setAttribute("id", 1);

And place it whereever you want to add it.

See more at HTML DOM Input Checkbox Object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM