Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

JQuery Integer (Numeric) Input (TextBox) Mask

4.21/5 (5 votes)
15 Jul 2015CPOL 12.6K   101  
How to change the html input to an integer (numeric) input (textbox) mask.

Introduction

With using JQuery (2.1.4), I changed (enforecd) html input to an integer (numeric) input (textbox) mask.

Sample Application

This sample application was developed by using Microsoft Visual Studio 2013

Download JQUERY_INTEGER_TEXTBOX_VERSION_1_0_0-noexe.zip

What Characters This Input Mask Accept?

With this JQuery code, you can use below characters in your textbox:

  • All of numbers in your keyboard (even numlock numbers)
  • TAB
  • SHIFT + TAB
  • LEFT ARROW KEY
  • SHIFT + LEFT ARROW KEY
  • RIGHT ARROW KEY
  • SHIFT + RIGHT ARROW KEY
  • DELETE
  • BACKSPACE
  • SHIFT + INS
  • CTRL + INS
  • CTRL + C
  • CTRL + V

Note that you should use the "integer" css class for each of your input htmls that you want to behave such as an integer (numeric) input mask. for example:

HTML
<input type="text" class="integer" />

Using the code

JavaScript
$(document).ready(function () {

    $("input.integer").keydown(function (e) {

        if (e.ctrlKey) {

            // CTRL + INS
            if (!((e.keyCode == 45) ||
                // CTRL + C
                (e.keyCode == 67) ||
                // CTRL + V
                (e.keyCode == 86))) {

                e.preventDefault();

            }

        }
        else {

            if (e.shiftKey) {

                // SHIFT + TAB
                if (!((e.keyCode == 9) ||
                    // SHIFT + LEFT ARROW KEY
                    (e.keyCode == 37) ||
                    // SHIFT + RIGHT ARROW KEY
                    (e.keyCode == 39) ||
                    // SHIFT + INS
                    (e.keyCode == 45))) {

                    e.preventDefault();

                }

            }
            else {

                // BACKSPACE
                if (!((e.keyCode == 8) ||
                    // TAB
                    (e.keyCode == 9) ||
                    // LEFT ARROW KEY
                    (e.keyCode == 37) ||
                    // RIGHT ARROW KEY
                    (e.keyCode == 39) ||
                    // DELETE
                    (e.keyCode == 46) ||
                    // NUMBER KEYS
                    ((e.keyCode >= 48) && (e.keyCode <= 57)) ||
                    // NUMLOCK KEYS
                    ((e.keyCode >= 96) && (e.keyCode <= 105)))) {

                    e.preventDefault();

                }

            }

        }

    });

});

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)