码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript全选和取消全选

时间:2016-08-02 23:58:00      阅读:353      评论:0      收藏:0      [点我收藏+]

标签:

<html>
    <head>
        <title>全选和取消全选</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script language="javascript">
            function checkAllorcancelAll(){
                //思路:1.获取checkbox的选中状态;1.1获取checkbox元素
                var chkElt = document.getElementById("chkElt");
                //1.2获取选中状态
                var checked = chkElt.checked;
                //2.若checked=true,选中所有复选框;
                //2.1获取所有复选框
                var allInterests = document.getElementsByName("interest");
                //2.2遍历取出每个复选框对象
                var mySpan = document.getElementById("mySpan");
                if(checked){
                    //全选,设置复选框的选中状态
                    for(var i=0;i<allInterests.length;i++){
                        allInterests[i].checked = true;
                    }
                    mySpan.innerHTML="取消全选";
                }else{
                    //取消全选
                    checked=false;
                    for(var i=0;i<allInterests.length;i++){
                        allInterests[i].checked = false;
                    }
                    mySpan.innerHTML="全选";
                }    
            }    
        </script>
    </head>
    <body>
        <input type = "checkbox" id="chkElt" onclick="checkAllorcancelAll()">
        <span id="mySpan">全选</span><br>
        运动<input type = "checkbox" name="interest" value="sport" /><br>
        音乐<input type = "checkbox" name="interest" value="music" /><br>
        美食<input type = "checkbox" name="interest" value="food" /><br>
        睡觉<input type = "checkbox" name="interest" value="sleep" /><br>
        跳舞<input type = "checkbox" name="interest" value="dance" /><br>
    </body>
</html>
</html>

 

JavaScript全选和取消全选

标签:

原文地址:http://www.cnblogs.com/wangqiang4518/p/5730998.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!