Add thousand comma separators to input type number

那年仲夏 提交于 2021-02-11 04:32:57

问题


I have this script that was maked by another memeber of stackoverflow but I need to put a comma separator for thousands numbers.

How I can do that?

(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" />

回答1:


  1. You can't put commas on a "number" input, so change it to "text".
  2. Since you can't use "toLocaleString" and toFixed together, a different solution is needed:

(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" />


来源:https://stackoverflow.com/questions/40093527/add-thousand-comma-separators-to-input-type-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!