1

Good day, I am creating a form that required the user to enter digits, the digits can be large in millions or billions, using the HTML input type="number", it gives the user some stress in counting the digits, I want to format the numbers are the user is typing to make it clear so that he/she will not type the wrong figure I intend using jquery keyup, because I am using CakePHP for the project, I tested this somewhere, but I was not getting the desired answer

    <form>
  <label for="amount">Amount</label>
  <input type="number" name="amount" id="amount" />
</form>

    <script>
  $(document).ready(function () {
      $("#amount").keyup(function () {
        $("#amount").toLocaleString();
      });
  });
</script>

Thank you in advance

KINGSLEY OKPARA
  • 549
  • 1
  • 5
  • 16
  • Hi, welcome to SO. You're calling $("#amount") but there's no element in your snippet with an id of "amount". Do you need to add id="amount" to your input? – Tim Barclay May 21 '20 at 15:30
  • https://stackoverflow.com/search?q=%5Bjavascript%5D+add+comma+to+input – freedomn-m May 21 '20 at 15:49
  • 1
    Does this answer your question? [Add thousand comma separators to input type number](https://stackoverflow.com/questions/40093527/add-thousand-comma-separators-to-input-type-number) – freedomn-m May 21 '20 at 15:50

1 Answers1

2

Hello here is a script that I found in another topic.

script credit: http://phpjs.org/functions/number_format/

function number_format (number, decimals, dec_point, thousands_sep) {
    // Strip all characters but numerical ones.
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}
<input type="number" value="0" oninput="document.getElementById('result').innerHTML = number_format(this.value, 0, ',', ' ')">
<br>
<span>Result: <b id="result">0</b> </span>
Adnane Ar
  • 683
  • 7
  • 11