使用它的'值选择动态复选框
To select a Dynamic checkbox using it's value
我需要使用它们的默认值选择一个复选框。我添加了下面的代码供参考。我的要求是,如果服务器端值为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>
我认为这可能是最有效的方法。
相关文章:
- d3基于用户选择动态更新节点
- JQuery--无法选择动态附加到表中的对象
- 如何根据用户选择动态更改多个复选框的编号
- JavaScript确认何时在表单中选择动态HTML字段
- 使用JQuery通过下拉选择动态更改PHP值
- 使用用户选择动态更新页面
- 在jquery中选择动态创建的元素
- 选择动态添加表单的元素
- 根据<选择>动态创建的表单不起作用
- j查询选择动态添加的表行的列数据
- Dojo 筛选选择 - 动态将下拉列表中的特定选项标记为禁用(灰显且不可选择)
- 选择动态创建的 html 元素而不单击
- 如何运行函数以选择动态添加
- Jquery 选择动态 ID
- 使用 Knockoutjs 根据用户的语言选择动态调整页面内容
- jQuery 选择动态创建的 html 元素
- 如何在JQuery中从Gallery View中选择动态图像
- 如何从AngularJS指令中选择动态生成的元素
- 选择动态创建的表中高亮显示的行,onclick事件
- 按类名选择动态更改的元素