Search code examples
javascripthtmlnumber-formattingnumeric

Add thousand separator with javascript when add input dynamically


I have problem when adding input dynamically with thousand separator, when I click add and the input form appears. it should be when I type the number it will be arranged in thousand separator. Please help me

$(document).ready(function(){
 $(document).on('click', '.add', function(){
  var html = '';
  html += '<tr>';
  html += '<td><input type="text" name="item_name[]" class="form-control inputnumber" onkeypress="return event.keyCode > 47 && event.keyCode < 58 || event.keyCode == 46" /></td>';
  html += '</tr>';
  $('#item_table').append(html);
 });

$('input.inputnumber').keyup(function(event) {
  if (event.which >= 37 && event.which <= 40) return;
  $(this).val(function(index, value) {
    return value
      // Keep only digits and decimal points:
      .replace(/[^\d.]/g, "")
      // Remove duplicated decimal point, if one exists:
      .replace(/^(\d*\.)(.*)\.(.*)$/, '$1$2$3')
      // Keep only two digits past the decimal point:
      .replace(/\.(\d{2})\d+/, '.$1')
      // Add thousands separators:
      .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
  });
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <div class="table-repsonsive">
     <table class="table table-bordered" id="item_table">
      <tr>
       <th><button type="button" name="add" class="btn btn-success btn-sm add">ADD</button></th>
      </tr>
     </table>
    </div>


Solution

  • You can use the NumberFormat object

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat

    $(document).ready(function() {
      $(document).on('click', '.add', function() {
        var html = '';
        html += '<tr>';
        html += '<td><input type="text" name="item_name[]" class="form-control inputnumber" ></td>';
        html += '</tr>';
        $('#item_table').append(html);
      });
    
      $('#item_table').change(function(event) {
        if (event.target.classList.contains("inputnumber")) {
          // remove any commas from earlier formatting
          const value = event.target.value.replace(/,/g, '');
          // try to convert to an integer
          const parsed = parseInt(value);
          // check if the integer conversion worked and matches the expected value
          if (!isNaN(parsed) && parsed == value) {
            // update the value
            event.target.value = new Intl.NumberFormat('en-US').format(value);
          }
        }
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="table-repsonsive">
      <table class="table table-bordered" id="item_table">
        <tr>
          <th><button type="button" name="add" class="btn btn-success btn-sm add">ADD</button></th>
        </tr>
      </table>
    </div>