menu

Sunday, January 19, 2014

JavaScript to Allow only Numbers and Dot

<html>
<head>
    <title></title>
    <script type="text/javascript">
        function ChkKeyPressed(e, str) {
            var keyNum;
            // IE
            if (window.event) { keyNum = e.keyCode; }
                // Netscape/Firefox/Opera/Chrome
            else if (e.which) { keyNum = e.which; }
            // Chk whether dot is available
            var isDot = str.value.indexOf(".");
            // Chk for second dot
            if (isDot > -1 && keyNum == 46) { return false; }
                // Allow first dot
            else if (keyNum == 46) { return true; }
                // Allow numeric char 0 to 9
            else if (keyNum <= 57 && keyNum >= 48) { return true; }
                // Block all other characters
            else { return false; }
        }
    </script>
</head>
<body>
    Enter your number:
    <input type="text" onkeypress="return ChkKeyPressed(event, this)" />
</body>

</html>

No comments:

Post a Comment