1. 程式人生 > >JavaScript 多選事件觸發

JavaScript 多選事件觸發

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script language="JavaScript">
        document.write("<br>-------------多選事件觸發------------------<br>");
        //1.當所有選項全部勾選時觸發全選按鈕事件
        function chageAll(){
            var x = 0;          //勾選位數
            var cblist = document.getElementsByName("like");
            var checkAll = document.getElementById("checkAll");
            for(i=0;i<cblist.length;i++){
                if(cblist[i].checked){
                    x++;
                }else{
                    x--;
                }
            }
            if(x==4){
                checkAll.checked=true;      //多選框全部選中時結果返回true
            }else{
                checkAll.checked=false;     //多選框沒有全部選中時結果返回false
            }
        }
         //2. 點選(全選/全不選)按鈕 觸發 勾選選項 事件
        function chageCheck(element){
            var cblist = document.getElementsByName("like");    //獲取所有name為like的多選控制元件
            if(element.checked){
                for(i=0;i<cblist.length;i++){
                    cblist[i].checked=true;
                }
            }else{
                for(i=0;i<cblist.length;i++){
                    cblist[i].checked=false;
                }
            }
        }
        //3.反選事件
        function unChecked() {
            var cblist = document.getElementsByName("like");    //獲取所有name為like的多選控制元件
            for(i=0;i<cblist.length;i++){
                if(cblist[i].checked){
                    cblist[i].checked=false;
                }else{
                    cblist[i].checked=true;
                }
            }
            chageAll();
        }

    </script>
</head>
<body>
    <p><input type="checkbox" name="like" onchange="chageAll()"/>JavaScript</p>
    <p><input type="checkbox" name="like" onchange="chageAll()"/>JavaBean</p>
    <p><input type="checkbox" name="like" onchange="chageAll()"/>JavaOop</p>
    <p><input type="checkbox" name="like" onchange="chageAll()"/>JavaWeb</p>
    <p><input type="checkbox" id="checkAll"  onclick="chageCheck(this)"/>全選/全不選</p>
    <p><input type="button" value="反選" onclick="unChecked()" /></p>
</body>
</html>