【问题标题】:Add thousand comma separators to input type number在输入类型编号中添加千位逗号分隔符
【发布时间】:2016-10-17 18:46:59
【问题描述】:

我有这个脚本是由 stackoverflow 的另一个成员制作的,但我需要为数千个数字添加一个逗号分隔符。

我该怎么做?

(function($) {
  $.fn.currencyInput = function() {
    this.each(function() {
      var wrapper = $("<div class='currency-input' />");
      $(this).wrap(wrapper);
      $(this).before("<span class='currency-symbol'>$</span>");
      $(this).change(function() {
        var min = parseFloat($(this).attr("min"));
        var max = parseFloat($(this).attr("max"));
        var value = this.valueAsNumber;
        if(value < min)
          value = min;
        else if(value > max)
          value = max;
        $(this).val(value.toFixed(2)); 
      });
    });
  };
})(jQuery);

$(document).ready(function() {
  $('input.currency').currencyInput();
});
.currency {
  padding-left:12px;
}

.currency-symbol {
  position:absolute;
  padding: 2px 5px;
}
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<input type="number" class="currency" min="0.01" max="2500.00" value="25.00" />

【问题讨论】:

标签: javascript html numbers separator


【解决方案1】:
  1. 您不能在“数字”输入中使用逗号,因此请将其更改为“文本”。
  2. 由于不能同时使用“toLocaleString”和 toFixed,因此需要不同的解决方案:

(function($) {
  $.fn.currencyInput = function() {
    this.each(function() {
      var wrapper = $("<div class='currency-input' />");
      $(this).wrap(wrapper);
      $(this).before("<span class='currency-symbol'>$</span>");
      $(this).val(parseFloat($(this).val()).toLocaleString(undefined, {minimumFractionDigits:2, maximumFractionDigits:2}));
      
      $(this).change(function() {
        var min = parseFloat($(this).attr("min"));
        var max = parseFloat($(this).attr("max"));

        var value = parseFloat($(this).val().replace(/,/g, ''));
        if(value < min)
          value = min;
        else if(value > max)
          value = max;
        $(this).val(value.toLocaleString(undefined, {minimumFractionDigits:2, maximumFractionDigits:2})); 
      });
    });
  };
})(jQuery);

$(document).ready(function() {
  $('input.currency').currencyInput();
});
.currency {
  padding-left:12px;
}

.currency-symbol {
  position:absolute;
  padding: 2px 5px;
}
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<input type="text" class="currency" min="0.01" max="2500.00" value="1125.00" />

【讨论】:

  • 大赞!
  • 如何将其更改为点分隔符?
  • @SoniSilalahi 运行 toLocaleString 后,您可以将逗号替换为您想要的任何内容 $(this).val(parseFloat($(this).val()).toLocaleString(undefined, {minimumFractionDigits:2, maximumFractionDigits:2}).replace(/,/g, ".")); $(this).val(value.toLocaleString(undefined, {minimumFractionDigits:2, maximumFractionDigits:2}).replace(/,/g, "."));
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-11
  • 1970-01-01
  • 2012-11-17
  • 1970-01-01
  • 2010-12-07
相关资源
最近更新 更多