javascript 使用 jQuery 获取复选框的值为 1/0
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19788689/
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
Get value of checkbox as 1/0 with jQuery
提问by user2738640
I want to get values of all input fields with jQuery. I can do that with following code. However if the input field is checkbox, and it is checked, it will return "on". How can I get the value as 1if checked?
我想用 jQuery 获取所有输入字段的值。我可以用以下代码做到这一点。但是,如果输入字段是复选框,并且被选中,它将返回“ on”。如果选中,如何将值设为1?
jQuery:
jQuery:
$('button').click(function() {
inputs = $('.input');
inputs.each(function() {
var value = $(this).val();
alert(value);
});
});
HTML:
HTML:
<input type="text" class="input" />
<input type="text" class="input" />
<input type="checkbox" class="input">
<button>Get values<button>
回答by antyrat
回答by Roko C. Buljan
var input = $('.input');
$('button').click(function() {
input.each(function() {
var val = this.type=="checkbox" ? +this.checked : this.value ;
alert( val );
});
});
What is does:
什么是:
this.type=="checkbox" // Test if HTMLElement type is checkbox // (Boolean)
?
+this.checked // if true // using '+', set boolean (true/false) to int (0/1)
:
this.value // if false // just get the value
;
Additional reading: Convert boolean result into number/integer
补充阅读:将布尔结果转换为数字/整数
回答by sudhAnsu63
回答by Praveen
回答by Halaster
Use .is(':checked') instead of getting the value. This will return it as a boolean instead of getting "on" if checked.
使用 .is(':checked') 而不是获取值。如果选中,这会将其作为布尔值返回,而不是“打开”。
回答by Joke_Sense10
Because you have not mentioned any value for checkbox.Try this:
因为你没有提到复选框的任何值。试试这个:
<input type="checkbox" class="input" value="1">