1

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);
    }
    
});
nquincampoix
  • 508
  • 1
  • 4
  • 17
paulinajr
  • 15
  • 1
  • 1
  • 6

2 Answers2

1

try with .prop instead of .attr()

$(function (){
    if($('#a_principal').val()== "true"){           
         $("input:checkbox").prop('checked',true);
    }else{
        $("input:checkbox").prop('checked', false);
    }
});

Js Fiddle Demo

Sachin
  • 40,216
  • 7
  • 90
  • 102
1

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'));  
PSL
  • 123,204
  • 21
  • 253
  • 243