Java 如果布尔值为真,如何选中复选框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19060402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to checked checkbox if boolean value is true?
提问by paulinajr
I'm working on jsp application and I have a form that has a checkbox, I retrieve data from my database which has a bit field named "principal", I can get the value of this field which is a boolean but I can't checked or unchecked the checkbox depending on the value of "principal".
我正在处理 jsp 应用程序,我有一个带有复选框的表单,我从我的数据库中检索数据,该数据库有一个名为“principal”的位字段,我可以获得这个字段的值,它是一个布尔值,但我不能根据“principal”的值选中或取消选中复选框。
Here's my JSP code:
这是我的 JSP 代码:
<tr>
<td>Principal:</td>
<td colspan="2">
<input type="checkbox" id="a_principal" name="a_principal" value="<%=directorio.isPrincipal()%>"/>
</td>
</tr>
Javascript code:
Javascript代码:
$(function (){
if('#a_principal' == true){
$("input:checkbox").attr('checked', true);
}else{
$("input:checkbox").attr('checked', false);
}
});
Thanks in advanced.
提前致谢。
采纳答案by Sachin
try with .prop
instead of .attr()
尝试.prop
代替.attr()
$(function (){
if($('#a_principal').val()== "true"){
$("input:checkbox").prop('checked',true);
}else{
$("input:checkbox").prop('checked', false);
}
});
回答by PSL
Using prop
to set checked property and get your if condition right. attr
is not guaranteed to work against boolean properties of element and prop is. See the difference here. Also the condition '#a_principal' == true
is always true.
利用prop
设置检查属性,让你如果条件合适的。attr
不能保证对 element 和 prop 的布尔属性有效。请参阅此处的区别。此外,条件'#a_principal' == true
始终为真。
$("input:checkbox").prop('checked', $('#a_principal').length);
// i dont know if you meant $('#a_principal').prop('checked') then
$("input:checkbox").prop('checked', $('#a_principal').prop('checked'));
//but here :checkbx generic selector will select a_principal as well, so be specific
Providing your complete html will help solving your issue in a better way however try this:
提供完整的 html 将有助于以更好的方式解决您的问题,但请尝试以下操作:
var $principal = $('#a_principal');
$("input:checkbox").not($principal).prop('checked', $principal.prop('checked'));