0

我需要使用它们的默认值选择一个复选框。我添加了以下代码以供参考。我的要求是,如果服务器端值为 1 并且默认复选框值也是 1 ,则应选择值为 1 的复选框而不使用复选框 ID。

提前致谢。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title> new document </title>
  <meta name="generator" content="editplus" />
  <meta name="author" content="" />
  <meta name="keywords" content="" />
  <meta name="description" content="" />
 </head>
 <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("#btnSubmit").click(function(){
        //alert("clciked");
            $(":checkbox").each(function(){
                //alert($(this).val()); 
                if($(this).val()==1){       // assume 1 is a server side value
                $("input[type=checkbox]:contains('1')").attr("checked","checked");
                                /*var checkboxDefaultValue = $("#sampleDiv").find(":checkbox").val();
                                    alert(checkboxDefaultValue + "chkDefVal");
                                    if( checkboxDefaultValue==1){
                                    $("input:checkbox:contains('1')").attr("checked","checked");
                                } */  
                }
            });
        });
    });

</script>
 <body>
 <div id="sampleDiv">
<input type="checkbox" id="chk1" value="1" class="sample" >1
<input type="checkbox" id="chk2" value="2" class = "sample" >2
<input type="checkbox" id="chk3" value="3" class = "sample" >3
</br>
</br>
</div>
<input type="button" id="btnSubmit" value ="Show Values">
 </body>
</html>
4

4 回答 4

2
//Use $(this) instead of  $("input[type=checkbox]:contains('1')") :
    <script type="text/javascript">
        $(document).ready(function(){
            $("#btnSubmit").click(function(){

                $(":checkbox").each(function(){
                    if($(this).val()==1){     
                    $(this).attr("checked","checked");
                    }
                });
            });
        });

    </script>
于 2013-04-29T04:39:17.637 回答
1

尝试这个:

if($(this).val()==1){
    $(this).prop("checked",true);
}

阅读更多prop http://api.jquery.com/prop

于 2013-04-29T04:32:18.627 回答
0

这里有两种使用 jQuery 的方法:

<script type="text/javascript">
$(document).ready(function () {
    $("#btnSubmit").click(function () {
        //Only use one of the following:
        // this way will only select the first checkbox with the specified value
        $('input:checkbox[value="1"]').first().prop('checked', true);
        // this way will select all checkboxes with the specified value
        $('input:checkbox[value="1"]').prop('checked', true);
    });
});
</script>

我认为这可能是最有效的方法。

于 2013-04-29T04:57:24.940 回答
0

您可以使用属性等于选择器来获取具有给定值的复选框

$(':checkbox[value="' + 1 + '"]').prop('checked', true)
于 2013-04-29T04:30:06.027 回答