美文网首页
JavaScript-复选框处理

JavaScript-复选框处理

作者: 测试探索 | 来源:发表于2022-06-21 22:53 被阅读0次

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type = "text/javascript" src="index.js"></script>
    </head>
    <body>
        <form>
            <input type="checkbox" name="interest" value="1"><label>游泳</label>
            <input type="checkbox" name="interest" value = "2"><label>爬山</label>
            <input type="checkbox" name="interest" value = "3"><label>看书</label>
            <input type="checkbox" name="interest" value = "4"><label>听歌</label>
            <input type="button" id = "btn1" value = "全选" onclick="checkInterest()">
            <input type="button" value = "反选" onclick="checkInterest1()">
    
        </form>
    </body>
    </html>
    

    index.js

    var flag = true;
    //全选与取消全选功能
    function checkInterest(){
        var interest = document.getElementsByName("interest");
        for(i=0;i<interest.length;i++){
            //等于true代表选中
            interest[i].checked = flag;
        }
        if(flag){
           document.getElementById("btn1").value = "取消全选";
        }else{
            document.getElementById("btn1").value = "全选";
    
        }
        flag = !flag;
    
    }
    
    //反选功能
    function checkInterest1(){
        var interest = document.getElementsByName("interest");
        for(i=0;i<interest.length;i++){
            //等于true代表选中
            interest[i].checked = !interest[i].checked;
        }
    
    }
    
    

    相关文章

      网友评论

          本文标题:JavaScript-复选框处理

          本文链接:https://www.haomeiwen.com/subject/lufnmrtx.html