In many cases, I have checkboxes as below

 <input type="checkbox" name="custom7" value="1" checked="checked"> <label for="custom7">Email me more info?</label> 

Now when the checkbox is checked the value should be 1 as in value=1 . If the checkbox is unchecked, I want the value to be zero as in value=0. How can I do this?

2

6 Answers

Just to be a butt and offer a slightly shorter answer:

$('input[type="checkbox"]').change(function(){ this.value = (Number(this.checked)); }); 
6

Thanks worked as in

$('#custom7').on('change', function(){ this.value = this.checked ? 1 : 0; // alert(this.value); }).change(); 

link:

Don't forget about the bitwise XOR operator:

$('input[type="checkbox"]').on('change', function(){ this.value ^= 1; }); 
$('input[type="checkbox"]').on('change', function(){ this.value ^= 1; console.log( this.value ) });
<label><input type="checkbox" name="accept" value="1" checked> I accept </label> <label><input type="checkbox" name="accept" value="0"> Unchecked example</label> <script src="//"></script>

Very simple way

<input type="hidden" name="is_active" value="0" /> <input type="checkbox" name="is_active" value="1" /> 

Change global checkbox behavior way

document.addEventListener('DOMContentLoaded', e => { for (let checkbox of document.querySelectorAll('input[type=checkbox]')) { checkbox.value = checkbox.checked ? 1 : 0; checkbox.addEventListener('change', e => { e.target.value = e.target.checked ? 1 : 0; }); } }); 

It makes no much sense because unchecked checkboxes are not sent to the server as said in the comments, but if you need a value in the server you can use a hidden field:

HTML:

<input type="checkbox" value="1" checked="checked" /> <input type="hidden" value="1" name="custom7" /> <label for="custom7">Email me more info?</label> 

jQuery:

$('#custom7').on('change', function(){ $('#hdncustom7').val(this.checked ? 1 : 0); }); 

Using this methods you will receive custom7 with 0 or 1 in the server

Souldn't you try google first? Try this.

$('#custom7').change(function(){ $(this).val($(this).attr('checked') ? '1' : '0'); }); 
3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.