views:

23

answers:

1

I'm trying to figure out why my javascript code is not restricting numeric input. Here's the code below:

(function(){
                if(window.addEventListener) window.addEventListener("load",init,false);
                else if(window.attachEvent) window.attachEvent("onload",init);

                function init() {
                    var keytest = document.getElementById("keytest");

                    function numericinput(event) {
                        var e = event || window.event;
                        var key = e.charcode || e.keyCode;  
                        var regex =/^\d+\.?\d{4}$/;
                        key = String.fromCharCode(key);     

                        if (!regex.test(key)) {
                                alert("something");

                            //if(e.preventDefault) e.preventDefault();
                            //if(e.returnValue) e.returnValue = false;
                            //return false;
                        }
                        else { //return true; 
                            alert("something else");
                         }                                      
                    }

                    if(keytest.addEventListener) keytest.addEventListener("keypress",numericinput,false);
                    else {
                        keytest.onkeypress = numericinput();
                    }
                }
            })();
A: 

You use e.charcode but it should be e.charCode

Your regexp is a bit off too, and you will need to deal with back-space etc.

You may as well just examine the keycode itself, see.

Alex K.

related questions