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

Viewed 2164

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.

2 Answers

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

Not sure what you are trying to do, but to have the function called on the element value you can have set onchange attribute, but if you already have a function that handle onchange and want to integrate it with this function please add to your question too and I will amend my answer accordingly.

function CurrencyFormat(el) {
    let val = el.value.split('.').join('');
    el.value = val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
<input type="text" class="form-control" name="number_one" id="number_one" onkeypress="CurrencyFormat(this)" >

Related