我如何确定复选框是否被选中? [英] How do I determine if a checkbox is checked?

查看:94
本文介绍了我如何确定复选框是否被选中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,我的表单不想获得复选框的值......我不确定它是否是我的编码,但是当我尝试 alert()值,我得到 undefined 作为结果。我有什么不对?

 < head> 
< script>
var lfckv = document.getElementById(lifecheck)。checked
function exefunction(){
alert(lfckv);
}
< / script>
< / head>
< body>
< label>< input id =lifechecktype =checkbox>生活< / label>
< / body>

编辑

< (){
alert(document.getElementById(lifecheck);}我尝试将它改为

  function exefunction ).checked); 
}

但是现在甚至不需要执行> execute 。发生了什么问题?

在函数内部放置 var lfckv 当该行被执行时,主体尚未被分析,元素lifecheck不存在。这工作得很好:

 < html> 
< head>
< script language =javascripttype =text / javascript>
function exefunction(){
var lfckv = document.getElementById(lifecheck)。checked;
alert(lfckv);
}
< / script>
< / head>
< body>
< label>< input id =lifechecktype =checkbox>生活< / label>
< button onclick =exefunction()>检查值< /按钮>
< / body>
< / html>


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:

<html>
    <head>
        <script language="javascript" type="text/javascript">
            function exefunction(){
                var lfckv = document.getElementById("lifecheck").checked;
                alert(lfckv);
            }
        </script>
    </head>
    <body>
        <label><input id="lifecheck" type="checkbox" >Lives</label>
        <button onclick="exefunction()">Check value</button>
    </body>
</html>

这篇关于我如何确定复选框是否被选中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆