0

I use JavaScript to create multiple checkboxes to be inserted into a table. Each checkbox is in one row. I give all of them the same name and class name.
But the problem is I can not create a function to be fired when I click that element. What I want to do is create a function to be fired by clicking on any created checkbox.

btnSave.onclick = function() {
var table = document.getElementById("table");
var row = table.insertRow(document.getElementById("table").rows.length);
var cellCHECK = row.insertCell(0);
var cellID = row.insertCell(1);
var cellNAME = row.insertCell(2);
var cellAGE = row.insertCell(3);

var checkbox = document.createElement("INPUT");
checkbox.type = "checkbox";
checkbox.name = "check";
checkbox.className = "check";
checkbox.id = document.getElementById("table").rows.length - 1;
checkbox.value = document.getElementById("table").rows.length - 1;
cellCHECK.appendChild(checkbox);
}
<table id="table">
            <tr>
                <th></th>
                <th>ID</th>
                <th>Name</th>
                <th>Age</th>
            </tr>
        </table>
        
<button class="btnSave" id="btnSave">Save</button>

2
  • 2
    I do not see an attempt in the question to make any event bindings Commented Nov 10, 2020 at 21:39
  • Look up jquery button on click for dynamically generated element. Commented Nov 10, 2020 at 21:41

1 Answer 1

2

Here's a modified version of your snippet that uses native JS onclick property to set an event handler for each checkbox.

btnSave.onclick = function() {
  // Make a new row in the table element.
  var table = document.getElementById("table");
  var row = table.insertRow(document.getElementById("table").rows.length);
  var cellCHECK = row.insertCell(0);
  var cellID = row.insertCell(1);
  var cellNAME = row.insertCell(2);
  var cellAGE = row.insertCell(3);

  // Create a checkbox element.
  var checkbox = document.createElement("INPUT");
  checkbox.type = "checkbox";
  checkbox.name = "check";
  checkbox.className = "check";
  checkbox.id = document.getElementById("table").rows.length - 1;
  checkbox.value = document.getElementById("table").rows.length - 1;
  
  // Set an event handler for it.
  checkbox.onclick = function() { alert('Checkbox clicked!') }
  
  // Put it in the DOM.
  cellCHECK.appendChild(checkbox);
}
<table id="table">
  <tr>
    <th></th>
    <th>ID</th>
    <th>Name</th>
    <th>Age</th>
  </tr>
</table>

<button class="btnSave" id="btnSave">Save</button>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.