1

Good morning,

I would like to use JavaScript to manipulate a number input field so that if only one decimal place is entered, a zero is added, and if no decimal place is given, even two.

Now I have tried the following:

///html

<input type="number" id="netpricePerSeat" name="netpricePerSeat" placeholder="0,00" step=".01" min="2.5" onchange="endingZeros(this)" onkeyup="endingZeros(this)" onclick="endingZeros(this)" pattern="[0-9]+([\,|\.][0-9]+)?">


///js
  function endingZeros(input) {
    var countDecimals = function(value) {
      if (Math.floor(value) !== value)
        if(value.toString().includes('.'))
          return value.toString().split(".")[1].length || 0;
        if(value.toString().includes(','))
          return value.toString().split(",")[1].length || 0;
      return 0;
    }

    if(!isNaN(input.value) && countDecimals(input) === 1) {
      input.value = input.value + '0';
    }
  }

Unfortunately it is not clear at all. Important, in the field you should be able to enter decimal with comma or dot, because the form should be for all countries

1 Answers1

0

First of all, you should remove your handler from the onkeyup event, because it doesn't allow the user to enter the second decimal character.

Then take into account that <input type="number" /> allows you to enter the characters "e", "-" and "_" as well (according to the spec, see more)

Try this one:

function endingZeros(input) {
    if (!isValidInput(input)) {
        return;
    }

    const decimalsCount = countDecimals(input.value);

    if (decimalsCount === 0) {
        input.value = input.value + '.00';

        return;
    }

    if (decimalsCount === 1) {
        input.value = input.value + '0';

        return;
    }

    return;

    function countDecimals(val = '') {
        const formattedVal = String(val).replace(/,/, '.');

        if (Number.isInteger(formattedVal)) {
            return 0;
        }

        return formattedVal.match(/\.(\d+)/)?.[1]?.length || 0;
    }

    function isValidInput(node) {
        return node && !Number.isNaN(node.value)
    }
}
<input type="number" id="netpricePerSeat" name="netpricePerSeat" placeholder="0,00" step=".01" min="2.5" onchange="endingZeros(this)" onkeydown="return event.keyCode !== 69 && event.keyCode !== 187 && event.keyCode !== 189" pattern="[0-9]+([\,|\.][0-9]+)?">
IgorL
  • 28
  • 5
  • It runs perfectly, but how could I add two zeros, when I only input 1 number, like this `8 => 8,00` –  Oct 08 '20 at 05:48