Auto populate Comma and Decimal in Text Box

試著忘記壹切 提交于 2019-12-06 06:20:55

It might be or might not be simpler by pure JS string functions but here is a regexp version.

The thing is, i couldn't find a way to group the entered number string into ??n nnn ... nnn nnn nn matches with regexp. However it relatively simple to get groups like nn nnn nnn ... nnn n??. This is the regex;

/(^\d{2})|(\d{1,3})(?=\d{1,3}|$)/g

So i reverse the string to start with as follows;

Array.prototype.reduce.call(str,(p,c) => c + p)

then applying the regex to my reversed string with .match(rex) would work like, "123456789" to yield [ '98', '765', '432', '1' ].

Then of course join them with . and , at proper positions with

.reduce((p,c,i) => i - 1 ? p + "," + c : p + "." + c)

and get 98.765,432,1. Well we just need to reverse this string again of course. So here is a working example.

function formatNumber(e){
  var rex = /(^\d{2})|(\d{1,3})(?=\d{1,3}|$)/g,
      val = this.value.replace(/^0+|\.|,/g,""),
      res;
      
  if (val.length) {
    res = Array.prototype.reduce.call(val, (p,c) => c + p)            // reverse the pure numbers string
               .match(rex)                                            // get groups in array
               .reduce((p,c,i) => i - 1 ? p + "," + c : p + "." + c); // insert (.) and (,) accordingly
    res += /\.|,/.test(res) ? "" : ".0";                              // test if res has (.) or (,) in it
    this.value = Array.prototype.reduce.call(res, (p,c) => c + p);    // reverse the string and display
  }
}

var ni = document.getElementById("numin");

ni.addEventListener("keyup", formatNumber);
<input id="numin" placeholder="enter number">

The res += /\.|,/.test(res) ? "" : ".0"; part takes care of prefixing a "0." when we only have the cents.

<input id="num" type="text" />

function addCommas(x) {
  var parts = x.toString().split(".");
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  return parts.join(".");
}

$('#num').keypress(function() {
  var numberTyped = $("#num").val();
  var convertedNum = addCommas(numberTyped);
  $("#num").val(convertedNum);

});

The script uses a regular expression to add commas. Passing a number like 23456789.12345 produces 23,456,789.12345, which is the desired result.

Second Example

http://jsfiddle.net/ezbao2a3/15/

Here's a solution that formats the number onkeyup, in order to get the actual value of the input.

The keypress event checks for valid keys (e.g. only numbers and backspace). This could probably be perfected and moved to a js event listener.

The formatter regular expression can also be adjusted to handle decimals.

Here's a snippet. Hope it helps.

isNumberKey = function(evt) {
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  if (charCode != 46 && charCode > 31 
      && (charCode < 48 || charCode > 57))
    return false;

  return true;
}

var textInput = document.getElementById('txtChar');

textInput.addEventListener('keyup', function(evt){
    var n = parseInt(this.value.replace(/\D/g,''),10);
    textInput.value = n.toLocaleString();
}, false);
<input id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar" />

I tried this solution and it worked. Import the below line in your script tag .

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.10/jquery.mask.js"></script>

Then on onLoad function , use the below lines:

$('#incomePerPeriod').mask("#,##0.00", {reverse: true});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!