js控制单选复选框(全选)

//获取单选按钮的选项值
        function f1() {
            //radio集合
            var radios = document.getElementsByName("sex");
            for (var i = 0; i < radios.length; i++) {
                if (radios[i].checked) {
                    alert(radios[i].value);
                    break;
                }
            }
        }

    <input type="checkbox" id="chkAll" id="btn" type="button" value="反选" /><br />
    <input id="childChk1" type="checkbox" value="cf"/>吃饭<br/>
    <input id="Checkbox2" type="checkbox" value="sj"/>睡觉<br/>
    <input id="Checkbox3" type="checkbox" value="dq"/>打球<br/>
//复选框的全选功能
function checkAll() {
            //触发事件对象,全选的checkbox
            var obj = event.srcElement;
            //所有的input标签
            var inputs = document.getElementsByTagName("input");
            for (var i = 0; i < inputs.length; i++) {
                //判断当前的对象是不是input对象,是不是checkbox
                if (inputs[i].type == "checkbox") {
                    inputs[i].checked = obj.checked;
                }
            }
        }
//给所有的 子checkbox注册事件,如果所有的子checkbox都打勾了,则全选也打勾
        window.onload = function () {
            var inputs = document.getElementsByTagName("input");
            for (var i = 0; i < inputs.length; i++) {
                if (inputs[i].type == "checkbox") {
                    //去掉全选的那个chexkbox
                    if (inputs[i].id != "chkAll") {
                        //给每个子checkbox注册事件
                        inputs[i].onclick = function () {
                            //判断子checkbox是不是被选中了
                            //假设所有的都被选中
                            var isCheckAll = true;
                            for (var j = 0; j < inputs.length; j++) {
                                if (inputs[j].type == "checkbox" && inputs[j].id != "chkAll") {
                                    //判断子的checkbox是否被选中
                                    if (!inputs[j].checked) {
                                        isCheckAll = false;
                                        break;
                                    }
                                }
                            }
                            //设置全选状态
                            document.getElementById("chkAll").checked = isCheckAll;
                        }
                    }

                }

            }

        }



















本文转自蓬莱仙羽51CTO博客,原文链接:http://blog.51cto.com/dingxiaowei/1366609,如需转载请自行联系原作者


上一篇:Bootstrap系列 -- 17. 复选框checkbox和单选择按钮radio


下一篇:Docker-配置连接多个镜像仓库