Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Quote:
I have creating a html table with javascript function in a page. and i need to create a checkbox in each of the last column in each row from my table1 and if the checkbox is checked then the elements of table1 is to be added to table2 without checkbox. I don't know how to do that. anyone can help me? please give me an example for that.


What I have tried:

  const a = ["a1", "a2", "a3"];
const b = ["b1", "b2", "b3"];
const c = ["c1", "c2", "c3"];
let html = [];
window.addEventListener("load", function() {
  html.push("<table><tbody>");
  for (var i = 0; i < a.length; i++) {
    j = i + 1;
    html.push(`<tr><td>${j}</td><td>${a[i]}</td><td>${b[i]}</td><td>${c[i]}</td>`);
    html.push(`<td><input type="checkbox"  value="${i}" name="code"></td></tr>`)
  }
  html.push("</tbody></table>");
  document.getElementById("container").innerHTML = html.join("");
});

$(document).ready(function() {
    var y = 0;
    $("input[type='checkbox']").onclick(function(){
    var code1 = $("input[name='code']:checked").val();
    for (var x = 0; x < code1.length; x++) {
        if ($(this).prop("checked") == true){
            window.addEventListener("load", function() {
                html1.push("<table><tr>");
                y = y + 1;
                html1.push(`<tr><th>${y}</th><td>${a[x]}</td><td>${b[x]}</td><td>${c[x]}</td></tr>`);
                html.push("</table>");
            });
        });
Posted
Updated 19-Aug-20 1:00am

1 solution

Here's the sense of how to do this (not the code!). It is not the most efficient way to do it but is easily understandable. It will modify the second table every time you check (or uncheck) any of the boxes in the first table.

1 - give your checkbox a name associated with the value (which is your row no.). This should be a generated name like 'ckk'+i
2 - create a oncheck or oncheckedchanged event for each checkbox - all going to the same function (whatever best suits you)
3 - the function is written so as to go through the list of checkboxes using their generated names by looping through them. This function builds a string for the table contents from only the checked boxes. This string is regenerated from empty every time a boxes check is changed.
4 - the right side table is refreshed using document.getElementByID('table_two_ID').innerHTML with the finished string from the function.

This method builds the table in the same order as the original but only with the checked items. It is not the only solution to this problem
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900