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

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

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

当前回答

你可以通过这两种方法得到值(true/false)

$("input[type='checkbox']").prop("checked");
$("input[type='checkbox']").is(":checked");

其他回答

$("#ans").attr('checked') 

会告诉你是否检查过。您还可以使用第二个参数true/false来选中/取消选中复选框。

$("#ans").attr('checked', true);

对于每个注释,在可用时使用prop而不是attr。例句:

$("#ans").prop('checked')

试试这个

$('input:checkbox:checked').click(function(){
    var val=(this).val(); // it will get value from checked checkbox;
})

此处flag为真,否则为假

var flag=$('#ans').attr('checked');

同样,这将使复选框

$('#ans').attr('checked',true);
<input type="checkbox" id="ans" value="1" />

Jquery: Var test= $("#ans").is(':checked') 它返回true或false。

在你的职责范围内:

$test =($request->get ( 'test' )== "true")? '1' : '0';

首先检查值是否被检查

$("#ans").find("checkbox").each(function(){
    if ($(this).prop('checked')==true){ 
    var id = $(this).val()
    }
});

否则设置为0值

@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 );

提示“不”