Search code examples
jquerynumber-formatting

jQuery input box automatically add DOT into Currency format and only allow numeric


I have input box with condition to allow only numeric. While adding numeric automatically add DOTs as currency format like following.

100 = 100
1000 = 1.000
10000 = 10.000
1000000 = 100.000
1000000 = 1.000.000


<input type="text" class="form-control" name="number_one" id="number_one" onkeypress="return event.charCode >= 48 && event.charCode <= 57" onkeyup="return CurrencyFormat(this.value)">

Can anyone please guide me how to call function value.

I found following useful but How to modify this function to automatically to add Dots into input box value and condition to only allow numbers.

function getNumberWithCommas(number) {
    return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}

Thank you.


Solution

  • Check following snippet demo.

    $('input.numberformat').keyup(function(event) {
    
      // skip for arrow keys
      if(event.which >= 37 && event.which <= 40) return;
    
      // format number
      $(this).val(function(index, value) {
        return value
        .replace(/\D/g, "")
        .replace(/\B(?=(\d{3})+(?!\d))/g, ".")
        ;
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <input class="numberformat">