2013-04-29 52 views
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> 
+0

复选框值从数据库中来,它的顺序可能被改变,所以不可能使用复选框ID – Vignesh 2013-04-29 04:30:11

回答

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> 
+0

我想你的代码,它的工作对你的帮助很好,谢谢 – Vignesh 2013-04-29 04:48:03

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> 

我想这可能是做的最有效方式。