Text Input allow only Integer input in angularjs

前端 未结 7 1028
梦如初夏
梦如初夏 2021-01-04 19:45

I want to set the html input[number] to allow only integer input (not float).

Basically, the html input

7条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-04 20:31

    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:

      
      
    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:

    Check out the Plunker

提交回复
热议问题