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".
Here's my JSP code:
<tr>
<td>Principal:</td>
<td colspan="2">
<input type="checkbox" id="a_principal" name="a_principal" value="<%=directorio.isPrincipal()%>"/>
</td>
</tr>
Javascript code:
$(function (){
if('#a_principal' == true){
$("input:checkbox").attr('checked', true);
}else{
$("input:checkbox").attr('checked', false);
}
});
Thanks in advanced.
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.
$("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:
var $principal = $('#a_principal');
$("input:checkbox").not($principal).prop('checked', $principal.prop('checked'));
try with .prop
instead of .attr()
$(function (){
if($('#a_principal').val()== "true"){
$("input:checkbox").prop('checked',true);
}else{
$("input:checkbox").prop('checked', false);
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.