简体   繁体   中英

Create Checkbox on table with JavaScript

I'm building an app and on this app I have to add items on a table, and I would like to add a checkbox on each line that I add, but I'm having troubles on trying to do that. Would you know how to add a checkbox on each line that I add on the table?

below is the code where I add line per line to my table

function addDataToTbody(nl, data) { // nl -> NodeList, data -> array with objects
  data.forEach((d, i) => {
    var tr = nl.insertRow(i);
    Object.keys(d).forEach((k, j) => { // Keys from object represent th.innerHTML
      var cell = tr.insertCell(j);
      cell.innerHTML = d[k]; // Assign object values to cells   
    });
    nl.appendChild(tr);
  })
}

I tried to do something like

tr.append("<td> <div class='form-control'>\
    <input type='checkbox' /> \
    <label for='chk'/>select</div>\
</td>");

But that just adds a text to my table and not the checkbox itself.

<div id="table-wrapper" class="table-responsive">
      <table class="table table-hover" id="PartData">
           <thead>
               <tr>
                   <th scope="col">#</th>
                   <th scope="col">FUNÇÃO</th>
                   <th scope="col">DESCRIÇÃO</th>
                   <th scope="col">QUANTIDADE</th>
                   <th scope="col">FABRICANTE DO PAINEL</th>
                   <th scope="col">PEÇA</th>
                   <th scope="col">REVISÃO</th>
               </tr>
           </thead>
           <tbody>
               <tr>
               </tr>
           </tbody>
       </table>
   </div>

above is my HTML code.

Thanks in advance!

As Teemu said in the comments, the solution was "Create the cell in the loop like you've created the other cells. Then, instead of append, use insertAdjacentHTML to add the HTML for the button. Notice, that this has to be done after setting innerHTML, otherwise the said property overrides everything what was in the cell."

So that's my final function:

function addDataToTbody(nl, data) { // nl -> NodeList, data -> array with objects
  data.forEach((d, i) => {
    var tr = nl.insertRow(i);
    
    //cell2.type = checkbox;
    Object.keys(d).forEach((k, j) => { // Keys from object represent th.innerHTML
      console.log(j)
      var cell = tr.insertCell(j);
      cell.innerHTML = d[k]; // Assign object values to cells   
    });
    
    tr.insertAdjacentHTML('beforeEnd', "<td> <div class='form-control'>\
    <input id = 'deleteChck' type='checkbox' /> \
    <label for='chk'/>Delete</div>\
    </td>");

    nl.appendChild(tr);
  })
}

And it works

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