一起学习网 一起学习网


JQ实现checkbox全选中以及获得选中的checkbox的值

前端 JQ实现checkbox全选中以及获得选中的checkbox的值,一起学习网, 学习交流平台, 在线学习, 学习资源, 教育平台, 学习社区, 学生论坛, 学习工具, 学习技巧, 学习经验 09-06

$('#this').attr('checked'); 返回的是checked或者是undefined,不是原来的true和false了。解决方法:

上面写法是JQ1.6之前的版本。

JQ1.6之后或更高版本写法:

/获取是否选中 
var isChecked = $('#cb').prop('checked'); 
//或 
var isChecked = $('#cb').is(":checked"); 
//设置选中 
$('#cb').prop('checked',true);

分析了其中的原因,可以这样理解: 
JQ将“属性”与“特性”做了区别,属性指的是“name,id”等等,可用attr设置,特性指的是“selectedIndex, tagName, nodeName,checked”等等。 

 所以:JQ1.6之后,可以通过attr方法去获得属性,通过prop方法去获得特性

$("#cb").attr("value"); //获取属性,正确返回value 值  
$("#cb").attr("checked"); //undefined 
$("#cb").prop("checked"); //true or false

演示例子:

html代码:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Simple jsp page</title>
    <script type="text/javascript" src="../js/jquery-1.3.2.js"></script>
    <script type="text/javascript" src="../js/checkbox.js"></script>

</head>
<body>
<form action="#" method="post">
    <input type="checkbox" id="select"/> 全选<br/>
    <input type="checkbox" value="1" name="items"><br/>
    <input type="checkbox" value="2" name="items"><br/>
    <input type="checkbox" value="3" name="items"> <br/>
    <input type="checkbox" value="4" name="items"> <br/>
    <input type="checkbox" value="5" name="items"> <br/>
    <input type="checkbox" value="6" name="items"> <br/>
    <input type="checkbox" value="7" name="items"> <br/>
    <input type="checkbox" value="8" name="items"> <br/>
    <input type="checkbox" value="9" name="items"> <br/>
    <input type="checkbox" value="10" name="items"> <br/>
    <input type="checkbox" value="11" name="items"> <br/>

    <input type="submit" id="submit" value="提交">
</form>
</body>
</html>

js代码:

$(function() {
    $("#select").click(function() {
        if ($(this).attr("checked")) {
            $("input[name=items]").each(function() {
                $(this).prop("checked", true);
            });
        } else {
            $("input[name=items]").each(function() {
                $(this).prop("checked", false);
            });
        }
    });
    //得到选中的值,ajax操作使用
    $("#submit").click(function() {
        var text="";
        $("input[name=items]").each(function() {
            if ($(this).prop("checked")) {
                text += ","+$(this).val();
            }
        });
         alert(text);
    });
});



编辑:一起学习网