Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the value of checkbox to true or false with jQuery

Tags:

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?

like image 475
Rene Zammit Avatar asked Nov 30 '11 15:11

Rene Zammit


People also ask

How check checkbox is true or false in jQuery?

$("#checkbox1"). prop('checked', true);

How do you check if a checkbox is true or false?

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.

How can I get checkbox value in jQuery?

To get the value of the Value attribute you can do something like this: $("input[type='checkbox']"). val();


2 Answers

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'); 
like image 174
Nicola Peluchetti Avatar answered Sep 19 '22 00:09

Nicola Peluchetti


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');      } }); 
like image 20
Jose Vega Avatar answered Sep 20 '22 00:09

Jose Vega