Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I append a new row to the body of a table in HTML using a javascript function that acts on a checkbox click?

I’ve been using the following resources:

And my HTML code with the javascript function is as follows:

<!doctype html>
<html>
<head>
<h1>Checkbox Test</h1>
</head>
    <body>
        <table class="tb" id="checky">
            <thead>
              <tr>
                <th>Checkbox 1</th>
                <th>Checkbox 2</th>
              </tr>
            </thead>
            <tbody>
                <tr>
                  <td><input type="checkbox" name="Team1_checkbox" id="1" onchange="doalert(this)"  /> &nbsp; </td> 
                  <td><input type="checkbox" name="Team2_checkbox" id="2" onchange="doalert(this)" /> &nbsp; </td>
                </tr>
            </tbody>
        </table>
        <script>
            function doalert(checkboxElem) {
              if (checkboxElem.checked) {
              
            var table=document.getElementByID("checky");
            var row=table.insertRow(0);
            
            alert("checked");
            
            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);

            cell1.innerHTML = "NEW CELL1";
            cell2.innerHTML = "NEW CELL2";

              } else {
                alert("notchecked");
              }
            }
        </script>
    </body>
</html>

The checkbox when checked does nothing but when unchecked it does display the alert, so I’m not quite sure what the issue is.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In JavaScript, function names are case sensitive.
You have bug in line:

 var table=document.getElementByID("checky");

Should be:

 var table=document.getElementById("checky");

Change function name getElementByID -> getElementById.

Correct this small bug and everything will work.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading