![](/img/trans.png)
[英]Javascript to check whether a checkbox is being checked or unchecked
[英]How to check if a checkbox is checked or unchecked with javascript?
我正在嘗試檢查天氣復選框被選中或未選中。 這是我的代碼:
<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>
當我點擊它時,它只會提醒未選中
提前致謝
嘗試
< 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 >
它似乎對我有用 - 請看這個小提琴。 請注意,事件偵聽器是由 Javascript 添加的,而不是使用內聯onclick
語法。
通過使用控制台或警告 document.forms[0].help_text,確保您正確引用了 object。 這很可能不是正確的參考。
alert(document.forms[0].help_text);
您的代碼非常好,但不是很好。 例如,當許多人在 1 次取消單擊后單擊復選框時,復選框將重新開始。 我的英語太糟糕了,我無法解釋但是:您選中了許多復選框,然后落在 if 語句中。 然后取消單擊一個,這是下降的 else 語句。 並檢查掉下來的。 你的代碼是這樣開發的:
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.