I’ve been using the following resources:
- https://www.w3schools.com/jsref/met_table_insertrow.asp
- https://www.w3resource.com/javascript-exercises/javascript-dom-exercise-5.php
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)" /> </td>
<td><input type="checkbox" name="Team2_checkbox" id="2" onchange="doalert(this)" /> </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.
>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.