简体   繁体   English

如何使用 javascript 检查复选框是选中还是未选中?

[英]How to check if a checkbox is checked or unchecked with javascript?

I am trying to check weather a checkbox is checked or unchecked.我正在尝试检查天气复选框被选中或未选中。 This is my code:这是我的代码:

<script type="text/javascript">
function EnableDisableToolTip() {
    if (document.forms[0].help_text.checked) {
        alert("Checked");
    }
    else if (!document.forms[0].help_text.checked) {
    alert("Unchecked");
    }        
}
</script>


<div id="tooltiponoff">
<form action="">
@Html.CheckBox("help_text", true, new { id = "help_text", onclick = "EnableDisableToolTip()" })Hjælpetekst
</form>
</div>

It only alerts Unchecked when i click it当我点击它时,它只会提醒未选中

Thanks in advance提前致谢

try尝试

< script type="text/javascript" >
function EnableDisableToolTip(Control) {
    if (Control.checked) {
        alert("Checked");
    }
    else {
    alert("Unchecked");
    }        
}
< /script >


< div id="tooltiponoff" >
< form action="" >
@Html.CheckBox("help_text", true, new { id = "help_text", onclick = "EnableDisableToolTip(this)" })Hjælpetekst
< /form >
< /div >

It seems to work for me - please see this fiddle .它似乎对我有用 - 请看这个小提琴 Note that the event listener is added by Javascript, instead of using the inline onclick syntax.请注意,事件侦听器是由 Javascript 添加的,而不是使用内联onclick语法。

Make sure you are correctly referencing the object by using the console or alerting document.forms[0].help_text.通过使用控制台或警告 document.forms[0].help_text,确保您正确引用了 object。 It's very likely it's not the right reference.这很可能不是正确的参考。

alert(document.forms[0].help_text);

Your code is very well but not greatable.您的代码非常好,但不是很好。 For example when many click the checkbox after 1 unclick then checkbox is start over.例如,当许多人在 1 次取消单击后单击复选框时,复选框将重新开始。 My English so bad i cannot explain But: You check many checkbox and then fall the if statement.我的英语太糟糕了,我无法解释但是:您选中了许多复选框,然后落在 if 语句中。 And then unclick one, this is falling else statement.然后取消单击一个,这是下降的 else 语句。 And checked ones falling down.并检查掉下来的。 Your code is developing like this:你的代码是这样开发的:

            var count = 0;
            function Tik(Control) {
                if (Control.checked) {
                    count++;
                }
                else {
                    count--;
                }
                if (count > 0) {
                    document.getElementById("btnMessageDel").disabled = false;
                }
                else {
                    document.getElementById("btnMessageDel").disabled = true;
                }
            }

<input type="submit" id="btnMessageDel" name="btnMessageDel" class="btn btn-primary" value="Delete" form="messagesform" disabled />
<input type="checkbox" value="@MessageId" name="chkMessage" id="chkMessage" onclick="Tik(this)" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM