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" onclick="checkAll()"/>全选<input 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;
                        }
                    }

                }

            }
        }
上一篇:飞天加速计划·高校学生在家实践


下一篇:Qt之密码框不可选中、复制、粘贴、无右键菜单等