0

I need your help,

The javascript coding works flawlessly and achieves the desired result, but for some reason, it does not allow the keys on the number pad to typed into the input box. Most users would type in numbers using the numlock keys on the keyboard. How can the coding be modified so as to allow the keys on the seperate number pad on the keyboard to function?

<!DOCTYPE html>
<html>
    <body>
        <div>
            <input type="text" id="rownum">
        </div>
        <script type="text/javascript">
            document.getElementById('rownum').onkeydown = function(e) {
                var key = (window.event) ? event.keyCode : event.which;
                alert(key);
                if (key == 8) { // Delete key
                    return
                }
                else {
                    if ( isNaN( String.fromCharCode(key) ) ) return false;
                }
            }
        </script>
    </body>
</html>
Matt Bryant
  • 4,841
  • 4
  • 31
  • 46
John Smith
  • 1,639
  • 11
  • 36
  • 51

3 Answers3

0

The numbers in the numberpad have different keyCodes. Other keys like delete have the same keyCode in the normal keyboard and the numberpad, but the keyCode 8 (the one you have in your code) is for backspace, not Delete.

makmonty
  • 465
  • 3
  • 12
0

The sample code does not appear to be valid. I run it and get 'event is undefined'. This code works:

document.getElementById('rownum').onkeydown = function(e) {
            var key = e.keyCode || e.which; // <-- updated reference to event
            alert(key);
            if (key == 8) { // Delete key
                return
            }
            else {
                if ( isNaN( String.fromCharCode(key) ) ) return false;
            }
        };

But as @Portnoy said, you will likely need to handle different keyCodes.

Kevin Boucher
  • 16,426
  • 3
  • 48
  • 55
0

Proving that the array.indexOf(array) is supported:

Array.prototype.indexOf = function(obj, start) {
     for (var i = (start || 0), j = this.length; i < j; i++) {
         if (this[i] === obj) { return i; }
     }
     return -1;
}

then you can apply the following:

            document.getElementById('rownum').onkeydown = function(e) {

                var key = (window.event) ? event.keyCode : event.which;

                var keys = [8,37,39,46,96,97,98,99,100,101,102,103,104,105]

                var x = (keys.indexOf(key) > -1)

                if (x != true) {

                    if (isNaN(String.fromCharCode(key))) { return false }

                }
            }
John Smith
  • 1,639
  • 11
  • 36
  • 51