Restrict input to numbers

I use this to restrict keyboard inputs to accept only numbers.

This by the way relies on jQuery. Improvements are welcome in the comments.

The CSS Selector

<input type="number" class="restrict-to-numbers" placeholder="Enter a number here" />

The jQuery

$('.restrict-to-numbers').keydown(function (e) {
    return isNumber(e);
});

The JavaScript

function isNumber(event) {
    if (event) {
        var charCode = (event.which) ? event.which : event.keyCode;
        if (charCode != 190 && charCode > 31 &&
            (charCode < 48 || charCode > 57) &&
            (charCode < 96 || charCode > 105) &&
            (charCode < 37 || charCode > 40) &&
             charCode != 110 && charCode != 8 && charCode != 46)
        return false;
    }
    return true;
}
Advertisements

One thought on “Restrict input to numbers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s