I am using the JavaScript to disable keyboard if checkbox is not checked and to enable only numbers if checkbox is checked.
My code is.
<script type="text/javascript">
function isNumberKey(evt)
{
if(document.getElementById("check1").checked=false)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
else
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 1 && charCode < 127)
return false;
return true;
}
}
</script>
HTML code
<asp:CheckBox ID="check1" runat="server"/>
<asp:TextBox ID="tbxt1" runat="server" MaxLength="6" Width="200" onkeypress="return isNumberKey(event);" TextMode="Password" autocomplete="off" />
In default as checkbox is not checked so JavaScript is not allowing me to use my keyboard. This 开发者_运维知识库is fine. When I change my checkbox status to checked and tried pressing a key. OnKeyPress event the checkbox status is changing to unchecked. Is there anything wrong in my code?
You have a bug in your code, you need double equlas ==
to check an equality in javascript.
Like this:
if(document.getElementById("check1").checked==false)
Also, it can be very confusing to somebody else to read your code if you don't contain all conditional stuff within a pair of curly braces, even when it's a single line.
So I'd refactor it ever so slightly to be like this (just for clarity, I haven't really changed anything):
<script type="text/javascript">
function isNumberKey(evt)
{
if(document.getElementById("check1").checked==false)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
{
return false;
}
else
{
return true;
}
}
else
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 1 && charCode < 127)
{
return false;
}
else
{
return true;
}
}
}
</script>
精彩评论