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?
$("#checkbox1"). prop('checked', true);
Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.
To get the value of the Value attribute you can do something like this: $("input[type='checkbox']"). val();
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');
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'); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With