Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine if a checkbox is checked?

For some reason, my form does not want to get the value of a checkbox... I am not sure if it is my coding or not, but when I try and alert() the value, I get undefined as a result. What do I have wrong?

<head>   <script>     var lfckv = document.getElementById("lifecheck").checked     function exefunction(){       alert(lfckv);     }   </script> </head> <body>   <label><input id="lifecheck" type="checkbox" >Lives</label> </body> 

EDIT

I tried changing it to this

function exefunction() {     alert(document.getElementById("lifecheck").checked); } 

But now it doesn't even want to execute. What's going wrong?

like image 820
Sean Avatar asked Jan 21 '11 01:01

Sean


People also ask

Which method is used to check the status of checkbox?

prop() and is() method are the two way by which we can check whether a checkbox is checked in jQuery or not. prop(): This method provides an simple way to track down the status of checkboxes. It works well in every condition because every checkbox has checked property which specifies its checked or unchecked status.


2 Answers

Place the var lfckv inside the function. When that line is executed, the body isn't parsed yet and the element "lifecheck" doesn't exist. This works perfectly fine:

function exefunction() {    var lfckv = document.getElementById("lifecheck").checked;    alert(lfckv);  }
<label><input id="lifecheck" type="checkbox" >Lives</label>  <button onclick="exefunction()">Check value</button>
like image 129
Elian Ebbing Avatar answered Oct 13 '22 00:10

Elian Ebbing


You are trying to read the value of your checkbox before it is loaded. The script runs before the checkbox exists. You need to call your script when the page loads:

<body onload="dosomething()">

Example:

http://jsfiddle.net/jtbowden/6dx6A/

You are also missing a semi-colon after your first assignment.

like image 39
Jeff B Avatar answered Oct 13 '22 00:10

Jeff B