如何确定复选框是否被选中? [英] How do I determine if a checkbox is checked?
本文介绍了如何确定复选框是否被选中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
出于某种原因,我的表单不想获取复选框的值...我不确定这是否是我的编码,但是当我尝试使用 alert()
值,我得到 undefined
结果.我有什么问题?
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>
编辑
我试着把它改成这个
function exefunction() {
alert(document.getElementById("lifecheck").checked);
}
但现在它甚至不想execute
.怎么了?
But now it doesn't even want to execute
. What's going wrong?
推荐答案
将 var lfckv
放在函数内.执行该行时,主体尚未解析,元素 "lifecheck"
不存在.这工作得很好:
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>
这篇关于如何确定复选框是否被选中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文