使用JQuery获取被选中的checkbox的value值 以及全选、反选

复制代码
以下为使用JQuery获取input checkbox被选中的值代码:

<html>
    <head>
        <meta charset="gbk">
        <!-- 引入JQuery -->
        <script src="jquery-1.3.1.js" type="text/javascript"></script>
    </head>

    <body>
        <input type="checkbox" value="橘子" name="check">橘子1</input>
        <input type="checkbox" value="香蕉" name="check">香蕉1</input>
        <input type="checkbox" value="西瓜" name="check">西瓜1</input>
        <input type="checkbox" value="芒果" name="check">芒果1</input>
        <input type="checkbox" value="葡萄" name="check">葡萄1</input>
        
        <input type="button" value="方法1" id="b1">
        <input type="button" value="方法2" id="b2">


    </body>
    
    <script>
        //方法1
        $("#b1").click(function(){
            //$('input:checkbox:checked') 等同于 $('input[type=checkbox]:checked')
            //意思是选择被选中的checkbox
            $.each($('input:checkbox:checked'),function(){
                window.alert("你选了:"+
                    $('input[type=checkbox]:checked').length+"个,其中有:"+$(this).val());
            });
        });
        
        //方法2
        $("#b2").click(function(){
            $.each($('input:checkbox'),function(){
                if(this.checked){
                    window.alert("你选了:"+
                        $('input[type=checkbox]:checked').length+"个,其中有:"+$(this).val());
                }
            });
        });
    </script>
</html>
复制代码

 实现全选反选 注意用:prop

<ul id = "list-unstyled" class="list-unstyled">
    <li><input name="check" type="checkbox" value="9-DM"></li>
    <li><input name="check" type="checkbox" value="10-DM"></li>
    <li><input name="check" type="checkbox" value="11-DM"></li>
    <li><input name="check" type="checkbox" value="12-DM"></li>
</ul>

 

复制代码
    // 全选
   
    $('#allcheck').click(function(){

        $('input[name="check"]').prop('checked','true');
    });

    //反选
    $('#reversecheck').click(function(){
        $('input[name="check"]').each(function () {
            $(this).prop("checked", !$(this).prop("checked"));
        });

    });
复制代码

 

posted on   星河赵  阅读(46159)  评论(2编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示