Flag value 0 or 1

In many cases, I have the checkboxes below

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

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

+5
source share
6 answers

Thanks, as in

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

link: http://jsfiddle.net/WhQaR/

+7
source

Just be a butt and offer a slightly shorter answer:

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

Do not forget about 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="//code.jquery.com/jquery-3.3.1.min.js"></script> 
+5
source

Could you try Google first? Try it.

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

This doesn’t make much sense since the flags are not checked on the server, as indicated in the comments, but if you need a value on the server, you can use a hidden field:

HTML:

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

JQuery

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

Using these methods, you will get custom7 with 0 or 1 on the server

+2
source

This code works for me.

JQuery:

$('#custom7').on('change', function(){ var custom=$("#custom7").is(':checked')?1:0; }

-one
source

Source: https://habr.com/ru/post/1497640/


All Articles