Baptiste D.
Baptiste D.

Reputation: 115

Only numbers in input : detect "capsLock" on keypress

I made a function to prevent a user from entering anything other than numbers into a field (but allows useful keys like "backspace", "enter", etc ...)

Here a jsFiddle for the example: http://jsfiddle.net/cWHRp/1/

And the javascript code:

$('input').on('keypress', function (e) {
    if (
        // Allow "backspace", "tab", "enter", "escape" and "delete"
        ($.inArray(e.keyCode, [8, 9, 13, 27, 46]) !== -1) ||
        // Allow "shift + decimal point" (= delete on numpad)
        (e.shiftKey === true && e.keyCode ==  110) ||
        // Allow "Ctrl + A" and "Ctrl + C"
        (e.ctrlKey === true && ($.inArray(e.keyCode, [65, 67]) !== -1)) ||
        // Allow "end", "home", "left arrow", "up arrow", "right arrow" and "down arrow"
        (e.keyCode >= 35 && e.keyCode <= 39) ||
        // Allow "shift + classic numbers"
        (e.shiftKey === true && e.keyCode >= 48 && e.keyCode <= 57) ||
        // Allow numbers on numpad
        (e.keyCode >= 96 && e.keyCode <= 105)
    ) {
        return;
    }
    e.preventDefault();
});

It works well, even with shift + number. But I don't know how to detect that capsLock is ON when the user is typing on the keyboard.

Have you any idea to solve this problem please?

Thank you in advance!

Upvotes: 0

Views: 1136

Answers (3)

Ian Clark
Ian Clark

Reputation: 9347

OK, so first off as others have mentioned: why are you doing this?. @pawel has suggested some better approaches.

That said, using the KeyboardEvent.getModifierState() method, you can do the following:

$('input').on('keypress', function(e) {
  var isCapsLock = e.originalEvent.getModifierState("CapsLock");
  ...
});

Upvotes: 3

A. Wolff
A. Wolff

Reputation: 74420

You could use oninput event (taking care of paste value from contextmenu) and just use a regex to match all not numeric characters:

SEE DEMO

$('input').on('input', function (e) {
    this.value = this.value.replace(/\D/g,''); 
});

You could still use onkeyup/onpaste event instead, for older browsers which don't support oninput event.

Upvotes: 1

pawel
pawel

Reputation: 36965

Don't do this, this creates more problem than it solves. Here are some better solutions:

a) <input type="number" />

b) <input type="text" pattern="\d+" />

c) .replace(/[^\d]/g,'') in a change (or keyup) event listener

d) masked-input plugins

e) client + server-side validation (which you should use anyway)

Upvotes: 4

Related Questions