0

I want to replace a number over 100 with commas. Like 1000 to 1,000 and 1000000 to 1,000,000 etc. in HTML. I have found the code on here to do so but it only works with predetermined numbers being passed. I don't want it to work for a predetermined number but for any number typed into the box.

<label for="turnover">Estimated Monthly Card Turnover:</label><br />
    <span>&pound; </span><input type="text" id="turnover" maxlength="11" 
    name="turnover" size="10" required>*
    <br /><br />


<script type="text/javascript">
    $('#turnover').keydown(function(){
        var str = $(this).val();
        str = str.replace(/\D+/g, '');
        $(this).val(str.replace(/\B(?=(\d{3})+(?!\d))/g, ","));});


    </script>
  • 2
    Possible duplicate of [How to print a number with commas as thousands separators in JavaScript](https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript) – Peter B Sep 10 '18 at 15:48
  • Use Javascript's built-in localization API. – connexo Sep 10 '18 at 16:20
  • Use this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat – Jonathan Sep 10 '18 at 18:13

3 Answers3

0

There are a couple of issues with your code:

  1. It runs once when the page loads, not after that. I added a button to fix that.
  2. The id used in your code does not match the actual id of the input field.
  3. Input fields must be read and written using .val(). .text() works only for divs, spans etc.

Note that the conversion now works one time, after that it fails to properly parse the new text which now contains the comma(s).

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

function ShowComma() {
  console.clear();
  var val = parseInt($("#comma").val());
  console.log(val);
  val = numberWithCommas(val);
  console.log(val);
  $("#comma").val(val);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="turnover">Estimated Monthly Card Turnover:</label><br />
<span>&pound; </span><input type="value" id="comma" maxlength="30" name="turnover" size="10" required>*
<button onclick="ShowComma()">Show Comma</button>
Peter B
  • 22,460
  • 5
  • 32
  • 69
  • That's all well and good, I've used the onclick action to complete a search before. I just would love it if would automatically update with commas as soon as you type in the numbers. I've searched high and low for this answer and cannot seem to find it anywhere. – QwertyOvBfd Sep 10 '18 at 16:26
  • i have got this far now: `
    £ *

    ` Now it will put commas in but it is a bit random!
    – QwertyOvBfd Sep 10 '18 at 16:31
0

I created a solution using pure javascript.

function onChange(el) {
    var newValue = el.value.replace(/,/g, '');
    var count = 0;
    const last = newValue.substring(newValue.length - 1, newValue.length); // last input value

    // check if last input value is real a number
    if (!isNumber(last)) {
        el.value = el.value.substring(0, el.value.length - 1);
        return;
    }

    newValue = newValue.split('')
        .reverse().map((it) => {
            var n = it;
            if (count > 0 && count % 3 == 0) n = n + ',';
            count++;

            return n;
        })
        .reverse().join('')

    el.value = newValue

    // document.getElementById('value').innerHTML = newValue
}

function isNumber(input) {
    return input.match(/\D/g) == undefined;
}
<label>Number</label>
<input id="numbers" onkeyup="onChange(this)">
  • Yes that works but in needs to replace the number in the box and not put it underneath the box. This is are real head scratcher and I don't think anyone has done this yet. – QwertyOvBfd Sep 11 '18 at 09:27
  • Hi @user5743264 I updated the solution to update the value on the input element. Check it now. – Romildo da Silva Sep 11 '18 at 14:48
  • Perfect Romildo da Silva. That's exactly what I was looking for. I can now use this on my website ;) – QwertyOvBfd Sep 13 '18 at 09:58
0

To finalise this I have putgetElementById functions in so that this will work with a wordpress contact form 7. This must be with a text field though as it will not work with the number field as it will now accept commas:

 <script>

document.getElementById("averagetrans").onkeyup = function() {onChange(this)};
document.getElementById("Turnover").onkeyup = function() {onChange(this)};

</script>


    <script type="text/javascript">

    function onChange(el) {
    var newValue = el.value.replace(/,/g, '');
    var count = 0;
    const last = newValue.substring(newValue.length - 1, newValue.length); // last input value

    // check if last input value is real a number
    if (!isNumber(last)) {
        el.value = el.value.substring(0, el.value.length - 1);
        return;
    }

    newValue = newValue.split('')
        .reverse().map((it) => {
            var n = it;
            if (count > 0 && count % 3 == 0) n = n + ',';   // put commas into numbers 1000 and over 
            count++;

            return n;
        })
        .reverse().join('')

    el.value = newValue

    // document.getElementById('value').innerHTML = newValue
}

function isNumber(input) {
    return input.match(/\D/g) == undefined;
}
</script>