如果复选框被选中,那么我只需要得到值为1;否则,我需要得到它为0。我如何使用jQuery做到这一点?

$("#ans").val()在这种情况下总是会给我一个right:

<input type="checkbox" id="ans" value="1" />

当前回答

@StefanBrinkmann的回答很好,但对初学者来说不完整(省略了变量赋值)。澄清一下:

// this structure is called a ternary operator
var cbAns = ( $("#ans").is(':checked') ) ? 1 : 0;

它是这样工作的:

 var myVar = ( if test goes here ) ? 'ans if yes' : 'ans if no' ;

例子:

var myMath = ( 1 > 2 ) ? 'yes' : 'no' ;
alert( myMath );

提示“不”

其他回答

使用.is(':checked')来确定它是否被检查,然后相应地设置你的值。

更多信息请点击这里。

你可以试试这个:

$('#studentTypeCheck').is(":checked");

Use:

$("#ans option:selected").val()
$('input:checkbox:checked').val();        // get the value from a checked checkbox

只需使用$(selector).is(':checked')

它返回一个布尔值。