Reputation: 2647
Here exactly I am trying to make my textbox to accept only numbers. I am able to detect keyCode but event.preventdefault() is not working.
complete html + javascript
<HTML>
<HEAD>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#textbox1").keydown(function(event) {
try
{
if (event.keyCode >= 48 && event.keyCode <= 57)
{
alert("valid number");
}
else
{
event.preventDefault();
alert("It's NAN");
}
}
catch(ex) {
alert('An error occurred and I need to write some code to handle this!');
}
event.preventDefault();
});
});
</script>
</HEAD>
<BODY>
<FORM>
<input type="text" id="textbox1">
</FORM>
</BODY>
</HTML>
here is the fiddle.
How do I achieve the same?
Upvotes: 2
Views: 5390
Reputation: 1849
As @dystroy said, you should change your keydown to keypress and you should delete the event.preventDefault();
near the end (the second one) to make the code work.
Upvotes: 0