lundi 23 août 2021

Change td background color based on onclick checbox

I have a javascript where it will change the td background color if I click the checkbox. Below is the javascript

function onload() {
            var tds = document.getElementsByTagName("td");
            for(var i = 0; i < tds.length; i++) {
                tds[i].onclick = 
                                function(td) { 
                                    return function() { 
                                        tdOnclick(td); 
                                    }; 
                                }(tds[i]); 
            }
            var inputs = document.getElementsByTagName("input");
            for(var i = 0; i < inputs.length; i++) {
                inputs[i].onclick = 
                                function(input){ 
                                    return function() { 
                                        inputOnclick(input); 
                                    };
                                }(inputs[i]); 
            }
        }
        function tdOnclick(td) {
            for(var i = 0; i < td.childNodes.length; i++) {
                if(td.childNodes[i].nodeType == 1) {
                    if(td.childNodes[i].nodeName == "INPUT") {
                        if(td.childNodes[i].checked) {
                            td.childNodes[i].checked = false;
                            td.style.backgroundColor = "white";
                        } else {
                            td.childNodes[i].checked = true;
                            td.style.backgroundColor = "#E4E978";
                        }
                    } else {
                        tdOnclick(td.childNodes[i]);
                    }
                }
            }
        }

Here's the td:

<body onload="onload()">
    <td>
       <label><input type="checkbox" class="hidden"></label>
    </td>
</body>

Right now when I click the td, it's working but the color not fill the whole td. You can refer screenshot above:

screenshot of td

I've tried remove the label, but it's still the same.

This is example how I want the color to fill the whole td:

screenshot of td

But I can't find the solution. Hope anyone can help.




Aucun commentaire:

Enregistrer un commentaire