[英]Get value of checkbox as 1/0 with jQuery
我想用jQuery获取所有输入字段的值。 我可以用以下代码来做到这一点。 但是,如果输入字段是复选框,并且选中它,则它将返回“ on ”。 如果选中,如何将值设为1 ?
jQuery的:
$('button').click(function() {
inputs = $('.input');
inputs.each(function() {
var value = $(this).val();
alert(value);
});
});
HTML:
<input type="text" class="input" />
<input type="text" class="input" />
<input type="checkbox" class="input">
<button>Get values<button>
演示: http : //jsfiddle.net/yDKdT/
您需要检查元素的类型是否相等checkbox
:
if( $( this ).attr( 'type' ) === 'checkbox' ) {
value = +$(this).is( ':checked' );
}
提示: +
符号将布尔值转换为整数: 1/0
查看更新的jsFiddle
var input = $('.input');
$('button').click(function() {
input.each(function() {
var val = this.type=="checkbox" ? +this.checked : this.value ;
alert( val );
});
});
什么是:
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
;
附加读数: 将布尔结果转换为数字/整数
使用.is(':checked')而不是获取值。 这将返回它作为布尔值,而不是如果选中“开”。
你可以试试这个。
$('button').click(function() {
inputs = $('.input');
inputs.each(function() {
var value;
if( $( this ).attr( 'type' ) === 'checkbox' ) {
value = $(this).is( ':checked' ) ? 1: 0;
}else
{
value = $(this).val();
}
alert(value);
});
});
inputs.each(function () {
if($(this).attr('type') == "checkbox") {
value = $(this).prop('checked') == false ? 0: 1;
}
else {
value = $(this).val();
}
alert(value);
});
因为你没有提到checkbox的任何值。试试这个:
<input type="checkbox" class="input" value="1">
演示: http : //jsfiddle.net/yDKdT/3/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.