jQuery 复选框值 0 或 1

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18295811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:19:43  来源:igfitidea点击:

checkbox value 0 or 1

javascriptjqueryhtmlcss

提问by Hello Universe

In many cases, I have checkboxes as below

在许多情况下,我有如下复选框

 <input type="checkbox" name="custom7" value="1" id="custom7"
 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?

现在,选中复选框时,值应为值= 1。如果未选中该复选框,我希望该值为零,如 value=0。我怎样才能做到这一点?

回答by phatskat

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

只是为了提供一个稍微简短的答案:

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

回答by Hello Universe

Thanks worked as in

感谢工作

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

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

链接:http: //jsfiddle.net/WhQaR/

回答by Roko C. Buljan

Don't forget about the bitwise XORoperator:

不要忘记bitwise XOR运算符:

$('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>

回答by Daniele

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:

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:

jQuery:

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

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

使用此方法,您将custom7在服务器中收到0 或 1

回答by iiro

Souldn't you try google first? Try this.

你不先试试谷歌吗?尝试这个。

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

回答by Vitalicus

This code work for me.

这段代码对我有用。

jQuery:

jQuery:

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

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