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

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

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

当前回答

 $("#id").prop('checked') === true ? 1 : 0;

其他回答

 $("#id").prop('checked') === true ? 1 : 0;

我发现下面的方法对我有用,混合了其中一个答案,但是有if语句。

$('#checkbox').on('change', function () {
 let checkbox_true;
  checkbox_true = $('#checkbox').prop("checked") ? 1 : 0 ;
   if (checkbox_true === 1) {
     alert('Yes');
   } else {
     alert('no');
   }
})

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

它返回一个布尔值。

你还可以使用:

$("#ans:checked").length == 1;

首先检查值是否被检查

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

否则设置为0值