键入时用逗号显示数字

时间:2016-04-07 09:28:39

标签: javascript jquery

我在键入内容时尝试使用逗号显示数字。我不知道该怎么做。任何人都可以帮助我。

例如,在输入100000时,它应该在键入时自动显示1,00,000。我该怎么做?

1 个答案:

答案 0 :(得分:0)

使用angular..It非常谨慎。 试试这个...... create directive ..

<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@*" data-semver="1.2.10" src="http://code.angularjs.org/1.2.10/angular.js"></script>
    <script src="script.js"></script>
  </head>
  <body ng-app="app" ng-controller="myCtrl">
    <input type="text" add-commas />
  </body>

</html>

js file

angular.module('app', [])
.controller('myCtrl', function($scope) {})
.directive('addCommas', function(){
  return {
    link: function(scope, el, attrs){

      el.bind('focus', function() {

        // remove the commas again at focus
        el.val(el.val().replace(/,/g , ""));
      });

      el.bind('keypress', function(e) {

        // Only allows one dot and two commas
        validate(e, this);
      });

      el.bind('blur', function(){

        // Add two decimal digits 
        var value = parseFloat(Math.round(el.val() * 100) / 100).toFixed(2);

        // Add 1000 seperator
        value = addCommas(value);

        // Update inputs value
        el.val(value);
      });

      function addCommas(nStr) {
        nStr += '';
        var x = nStr.split('.');
        var x1 = x[0];
        var x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
      }

      function validate(evt, ele) {
        var theEvent = evt || window.event;
        var key = theEvent.keyCode || theEvent.which;
        key = String.fromCharCode( key );
        var value = ele.value + key;
        var regex = /^\d+(.\d{0,2})?$/;
        if( !regex.test(value) || key == ",") {
          theEvent.returnValue = false;
          if(theEvent.preventDefault) theEvent.preventDefault();
        }
      }
    }
  }
});

link可以帮助你...