简体   繁体   中英

Table with input checkbox check/Uncheck

I have a problem when doing the check in the accompanying table with color style works very well except when i click the first any checkbox does not change color style.

I paste the code and i use only javascript pure.

enter function valid(chk){
    var trckk = document.getElementsByTagName('tr');
    var parent = chk.parentNode.parentNode;
    var chkcomite = document.getElementsByName('idcom');
    var len = chkcomite.length;
    for(var i=0;i<len;i++){
        if(chkcomite[i].checked === true){
            if(chkcomite[i]!=chk && chk.checked){
                chkcomite[i].checked = false;
                for(var i=0;i<trckk.length;i++){
                    trckk[i].style.background='';
                    trckk[i].style.color='';
                }
            }
            parent.style.background='#EC1C24';
            parent.style.color='#FFF';  
        }else{
            parent.style.background='';
            parent.style.color='';
        }
    }
}

here

Can you help me?. thanks.

I think you must write the function like this

 function valid(chk) { var parent = chk.parentNode.parentNode; if (!chk.checked) { parent.style.background = ""; parent.style.color = ""; return; } var trckk = document.getElementsByTagName("tr"); var chkcomite = document.getElementsByName("idcom"); var len = chkcomite.length; for (var i = 0; i < trckk.length; i++) { trckk[i].style.background = ""; trckk[i].style.color = ""; } for (var i = 0; i < len; i++) { chkcomite[i].checked = false; chkcomite[i].parentNode.parentNode.style.background = ""; chkcomite[i].parentNode.parentNode.style.color = ""; } chk.checked = true; parent.style.background = "#EC1C24"; parent.style.color = "#FFF"; } 
 <table> <tr> <td> row 1 </td> <td> <input onchange="valid(this)" name="idcom" type='checkbox'> </td> </tr> <tr> <td> row 2 </td> <td> <input onchange="valid(this)" name="idcom" type='checkbox'> </td> </tr> <tr> <td> row 3 </td> <td> <input onchange="valid(this)" name="idcom" type='checkbox'> </td> </tr> </table> 

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