dpvhv66448 2018-05-06 13:03
浏览 50
已采纳

无法使用Javascript取消选中我的框

I have the following JS wich is actually working and Check all my boxes if the one of the top is checked (currently works) therefore I am unable to UNCHECK them by repeating the same process (unchecking the first box is not uncheckable) ._.

I have the following code wich actually call my function each time the checkbox is unchecked or checked:

function refresh_checkbox_list(){
    // document.getElementById('gdr_select_users').setAttribute("checked");

    (function() {
    var aa = document.querySelectorAll("input[type=checkbox]");
    for (var i = 0; i < aa.length; i++){
        aa[i].checked = true;
    }
})()
}

<input type="checkbox" name="gdr_select_all_users" id="gdr_select_all_users" onchange="refresh_checkbox_list()">
<input type="checkbox" name="gdr_select_users" id="gdr_select_users">

Just to say: I am a truly noob of Javascript, I know how I would process it in PHP so it does check and uncheck, but I dont know how does "if" statements work in JS, this is my actual problem..

I was thinking about an if statement that checks if my 1st box is checked then check all others boxes, then another statement wich do the exact reverse. Right?

I must admit that I have also found that JS on this website (an user wich had a similar case)

Thanks forward for any help!

  • 写回答

1条回答 默认 最新

  • donglian1523 2018-05-06 13:12
    关注

    Instead of using true use the checked state of #gdr_select_all_users.

    Also need to exclude #gdr_select_all_users from the loop. Can use not() in the query selector or better yet apply a common class to the user checkboxes

    function refresh_checkbox_list(){
        // get checked state of the "check all" box 
        let allChecked = document.getElementById('gdr_select_all_users').checked;
        (function() {
        var aa = document.querySelectorAll("input[type=checkbox]:not(#gdr_select_all_users)");
        for (var i = 0; i < aa.length; i++){
            // set other checkboxes to same state as the "check all"
            aa[i].checked = allChecked;
        }
    })()
    }
    Check all:<input type="checkbox" name="gdr_select_all_users" id="gdr_select_all_users" onchange="refresh_checkbox_list()">
    
    <br>
    User 1<input type="checkbox" name="gdr_select_users_1" >
    <br>
    User 2<input type="checkbox" name="gdr_select_users_2" >

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常