Skip to content Skip to sidebar Skip to footer

Add Thousand Comma Separators To Input Type Number

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?

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

Post a Comment for "Add Thousand Comma Separators To Input Type Number"