jquery checkbox学习记录

作者: 鸭梨山大哎 | 来源:发表于2017-06-30 10:02 被阅读39次

    checkbox有哪些主要操作?

    比如

    image.png

    利用js选择或者取消选择checkbox。

    这个的原理是依据checkbox的checked属性来进行的。

    <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js">
    </script>
    <script>
    $(function(){
        $("#cm").on("click",function(){
            //$("input:checkbox:first").attr("checked","true");
            //selcet the first checkbox and make it is selected
            //$("input:checkbox").eq(1).attr("checked","true");
            ////selcet the specific checkbox and make it is selected
            //$("input:checkbox").slice(0,2).attr("checked","true");
            //select both checkbox 
            //$("input:checkbox[value='1']").remove();
            //remove checkbox which value=1
            $("input:checkbox").each(function(){
                $(this).attr("checked",true)
            })
            //select all the checkbox use each function
            
            
        })
    })
    
    </script>
    <html>
        <label for="male">Male</label>
        <input type="checkbox" name="sex" id="male" value="0">
        <!--for is used for making mark for input element -->
        <br>
        <label for="female">Female</label>
        <input type="checkbox" name="sex" id="female" value="1">
        <br>
        <button id="cm">click me</button>
        
    </html>
    

    注意,选择第一个复选框用first。第二个可不是用second,而是用eq()过滤。

    补充一个

    获取checkbox的value属性.

    利用val方法

    alert($("input:checkbox:checked").val())
    

    判断选中元素个数

    var len=$("input:checkbox:checked").length;
    alert(len);
    // calculate how many elements is selected.
    

    限制一次只能选一个

    根据length属性判断选中个数就可以了。

    var len=$("input:checkbox:checked").length;
            if (len>1){
                alert("only one");
    

    总结

    牵扯到的知识点
    各种选择器的用法
    each遍历方法

    参考

    jquery操作复选框(checkbox)的12个小技巧总结jquery脚本之家
    jquery操作复选框(checkbox)的12个小技巧总结jquery脚本之家

    相关文章

      网友评论

        本文标题:jquery checkbox学习记录

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