复选框的值总是“打开”

这是我的复选框

超文本标示语言

<label class="checkbox">
<input id="eu_want_team" name="eu_want_team" type="checkbox">
</label>

JQuery

var eu_want_team = $('#eu_want_team').val();
alert(eu_want_team);

它总是显示为 ON,是否检查过。有什么问题吗?

38481 次浏览

Have a quick look at this answer for checking if a checkbox is checked.

How to check whether a checkbox is checked in jQuery?

But basically you want to do something like below to check its value:

if ($("#element").is(":checked")) {
alert("I'm checked");
}

Use .is(':checked') instead: Working jsFiddle

var eu_want_team = $('#eu_want_team').is(':checked');
alert(eu_want_team);

or as @Itay said in comments you can use jQuery's .prop() to get the checked property value:

alert($("#eu_want_team").prop("checked"));

i think this is what you want to do

$("#eu_want_team").click(function(){
alert($(this).is(':checked'));
}
<label class="checkbox">
<input id="eu_want_team" name="eu_want_team" type="checkbox" value="somevalue">
</label>


<script>
var ele = document.getElementById("eu_want_team");
if(ele.checked)
alert(ele.value)


</script>

This will work :

if ($('#element').is(":checked")) {
eu_want_team = 1;
} else {
eu_want_team = 0;
}
alert(eu_want_team);

Try this

if ( $('#element').is(':checked')){
alert(element);
}