Setting the value of checkbox to true or false with jQuery

I have a form with a checkbox. With jQuery I would like to set the value of the checkbox to TRUE if checked, and if it is not checked, the value will be set to FALSE. How I can do this please?


Solution 1:

You can do (jQuery 1.6 onwards):

$('#idCheckbox').prop('checked', true);
$('#idCheckbox').prop('checked', false);

to remove you can also use:

$('#idCheckbox').removeProp('checked');

with jQuery < 1.6 you must do

$('#idCheckbox').attr('checked', true);
$('#idCheckbox').removeAttr('checked');

Solution 2:

UPDATED: Using prop instead of attr

 <input type="checkbox" name="vehicle" id="vehicleChkBox" value="FALSE"/>

 $('#vehicleChkBox').change(function(){
     cb = $(this);
     cb.val(cb.prop('checked'));
 });

OUT OF DATE:

Here is the jsfiddle

<input type="checkbox" name="vehicle" id="vehicleChkBox" value="FALSE" />

$('#vehicleChkBox').change(function(){
     if($(this).attr('checked')){
          $(this).val('TRUE');
     }else{
          $(this).val('FALSE');
     }
});

Solution 3:

Use $('#id-of-the-checkbox').prop('checked', true_or_false);

In case you are using an ancient jQuery version, you'll need to use .attr('checked', 'checked') to check and .removeAttr('checked') to uncheck.