Checkbox value is always 'on'

JavascriptJqueryHtmlDomCheckbox

Javascript Problem Overview


this is my checkbox

HTML

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

Its always displaying ON, is it checked or not. Whats the problem with it?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

<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>

Solution 3 - Javascript

This will work :

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

Solution 4 - Javascript

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

https://stackoverflow.com/questions/901712/check-checkbox-checked-property-using-jquery

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

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

Solution 5 - Javascript

i think this is what you want to do

$("#eu_want_team").click(function(){
    alert($(this).is(':checked')); 
}

Solution 6 - Javascript

Try this

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2705406View Question on Stackoverflow
Solution 1 - JavascriptYotam OmerView Answer on Stackoverflow
Solution 2 - JavascriptVoonicView Answer on Stackoverflow
Solution 3 - JavascriptRoy M JView Answer on Stackoverflow
Solution 4 - JavascriptMarkView Answer on Stackoverflow
Solution 5 - JavascriptKimtho6View Answer on Stackoverflow
Solution 6 - JavascriptPadmanathan JView Answer on Stackoverflow