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 advan开发者_开发百科ce
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.
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 >
Make sure you are correctly referencing the object by using the console or alerting document.forms[0].help_text. 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. My English so bad i cannot explain But: You check many checkbox and then fall the if statement. And then unclick one, this is falling else statement. 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)" />
精彩评论