使用它的'值选择动态复选框

To select a Dynamic checkbox using it's value

本文关键字:选择 动态 复选框      更新时间:2023-09-26

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

Thanks in Advance.

<!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>
//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>

试试这个:

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

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

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

$(':checkbox[value="' + 1 + '"]').prop('checked', true)

这里有两种使用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>

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