Text Input allow only Integer input in angularjs

Cheetah Felidae picture Cheetah Felidae · Dec 1, 2015 · Viewed 31.4k times · Source

I want to set the html input[number] <input type="number" /> to allow only integer input (not float).

Basically, the html input[number] allow '.' to be entered for float input and I don't want that.

Is there a quick way to accomplish it in AngularJS?

Answer

Shyamal Parikh picture Shyamal Parikh · Dec 1, 2015

Here is how this can be achieved.

  1. With input type - 'text'

    Directive:

    app.directive('onlyNumbers', function () {
        return  {
            restrict: 'A',
            link: function (scope, elm, attrs, ctrl) {
                elm.on('keydown', function (event) {
                    if(event.shiftKey){event.preventDefault(); return false;}
                    //console.log(event.which);
                    if ([8, 13, 27, 37, 38, 39, 40].indexOf(event.which) > -1) {
                        // backspace, enter, escape, arrows
                        return true;
                    } else if (event.which >= 48 && event.which <= 57) {
                        // numbers 0 to 9
                        return true;
                    } else if (event.which >= 96 && event.which <= 105) {
                        // numpad number
                        return true;
                    } 
                    // else if ([110, 190].indexOf(event.which) > -1) {
                    //     // dot and numpad dot
                    //     return true;
                    // }
                    else {
                        event.preventDefault();
                        return false;
                    }
                });
            }
        }
    });
    

    HTML:

    <input type="text" only-numbers>
    
  2. With input type - 'number'

    Directive:

    app.directive('noFloat', function () {
    return  {
        restrict: 'A',
        link: function (scope, elm, attrs, ctrl) {
            elm.on('keydown', function (event) {
              if ([110, 190].indexOf(event.which) > -1) {
                    // dot and numpad dot
                    event.preventDefault();
                    return false;
                }
                else{
                  return true;
                }
            });
        }
    }
    });
    

    HTML: <input type="number" step="1" no-float>

Check out the Plunker