IT ppl
IT ppl

Reputation: 2647

event.preventdefault() not working on change event of textbox

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

Answers (2)

MIIB
MIIB

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.

JSFiddle Updated

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382284

Use the keypress event to intercept the change.

Demonstration

Upvotes: 5

Related Questions