I try to make lines dynamically, the problem is when I add a checkbox with label dynamically using javascript does not work. However the one I created with Html by default works correctly.
In fact I want the image that I added (on.png / off.png) replaces the checkbox. When I do it only with html (checkbox + label) the code works, but now I only want to create the element with Javascript, I can chow the label but it when I click It's not work.
This is all my code :
Main.html
<HTML>
<HEAD>
<TITLE> </TITLE>
<link rel="stylesheet" type="text/css" href="style.css" />
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.id = "id2" ;
cell1.appendChild(element1);
// Create label
var label = document.createElement("label");
label.for = "id2" ;
cell1.appendChild(label);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount + 1;
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "text";
cell3.appendChild(element2);
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</SCRIPT>
</HEAD>
<BODY>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<TABLE id="dataTable" width="350px" border="1">
<TR>
<TD><INPUT type="checkbox" name="chk" id="id1" /> <label for="id1" > </label> </TD>
<TD> 1 </TD>
<TD> <INPUT type="text" /> </TD>
</TR>
</TABLE>
</BODY>
</HTML>
style.css
input[type=checkbox] {
display:none;
}
input[type=checkbox] + label
{
background: url(images/off.png) no-repeat;
height: 64px;
width: 64px;
display:inline-block;
padding: 0 0 0 0px;
}
input[type=checkbox]:checked + label
{
background: url(images/on.png) no-repeat;
height: 64px;
width: 64px;
display:inline-block;
padding: 0 0 0 0px;
}
Help me please.
Change this
label.for = "id2" ;
to this
label.htmlFor = "id2" ;
Because some JavaScript implementations didn't allow keywords/reserved words as object properties, a workaround had to be made for the for
property, so they chose htmlFor
.
A similar situation was with .class
, which is why they use .className
.
Your problem is line 17, label.for = "id2" ;
that should be label.htmlFor = "id2";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With