简体   繁体   中英

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 = (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]); } } } }
 table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } label{ display:block; padding:20px; }.checkbx { text-align: center; /* center checkbox horizontally */ vertical-align: middle; /* center checkbox vertically */ }.hidden { display: none; }
 <body onload="onload()"> <table> <tr> <td> <label><input type="checkbox" class="hidden"></label> </td> <td> <label><input type="checkbox" class="hidden"></label> </td> </tr> </table> </body>

The color didn't fully fill the whole 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.

Please replace your css with the following css and then check.
    table {
        font-family: arial, sans-serif;
        border-collapse: collapse;
        width: 100%;
    }

    td, th {
        border: 1px solid #dddddd;
        text-align: left;
    }

    label{
        display:block;
        padding:20px;
    }

    .checkbx {
        text-align: center;
        /* center checkbox horizontally */
        vertical-align: middle;
        /* center checkbox vertically */
    }

    .hidden {
        display: none;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM