且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery中radio和checkbox的选中的另一种方式

更新时间:2022-08-21 11:03:46

<head>
    <title></title>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("input[name=sports]").val(["足球", "篮球"]);

            $("input[name=gender]").val(["男"]);
        });
    </script>
</head>
<body>
    
    <input type="radio" name="gender" value="男"/>男
    <input type="radio" name="gender" value="女"/>女
    <br /><br />
    <input type="checkbox" name="sports" value="足球"/>足球
    <input type="checkbox" name="sports" value="篮球"/>篮球
    <input type="checkbox" name="sports" value="乒乓球"/>乒乓球
    <input type="checkbox" name="sports" value="棒球"/>棒球
    <input type="checkbox" name="sports" value="乒乓球"/>乒乓球
</body>

上述的jQuery代码就把值为方括号里内容的控件选中了。

 

我们平时是这么干的

$('input:radio:first').attr('checked', 'checked');

或者

$('input:radio:first').attr('checked', 'true');