Restricting numeric input javascript problem

Posted by neitony on Stack Overflow See other posts from Stack Overflow or by neitony
Published on 2010-04-13T10:29:56Z Indexed on 2010/04/13 10:32 UTC
Read the original article Hit count: 185

Filed under:

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();
                    }
                }
            })();

© Stack Overflow or respective owner

Related posts about javascript-events