简体   繁体   中英

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?

Use the keypress event to intercept the change.

Demonstration

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM