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