JSFiddle - React, Tailwind, and code Playground

by Plippie Plop

HTML

<label>Valuta</label>
<div class="input-currency"><input type="text" name="item1" data-currency="EURO" placeholder="Valuta nl"></div>
<hr>
<input type="text" name="item2" placeholder="Valuta en"><br>
<input type="text" name="item3" data-currency="EURO" placeholder="Valuta nl"><br>
<input type="text" name="item4" placeholder="Valuta en"><br>
<input type="text" name="item5" data-currency="EURO" placeholder="Valuta nl"><br>

CSS

body{
  font-family:"Roboto";
}
input, .input-currency {
  position: relative;
  display:inline-block;

}


label + .input-currency::after {
 position:absolute;
  content: '€';
  z-index: 2;
  right: 0.25em;  
  color:grey;

}

JavaScript

const inputsValuta = document.querySelectorAll('input[data-currency="EURO"]');
for (var i = 0; i < inputsValuta.length; i++) {
  inputsValuta[i].addEventListener('keydown', checkCurrencyFormatting);
  inputsValuta[i].addEventListener('keyup', replaceCurrencyDotForComma);
}


function checkCurrencyFormatting(e) {

  console.log(e.key);

  if ((e.key === '.' || e.key === ',') && e.target.value.split(',').length === 2) {
    e.preventDefault();
    return false;
  }

  if (e.ctrlKey && e.key === "c") {
    return;
  }
  if (e.ctrlKey && e.key === "v") {
    return;
  }
   if (e.ctrlKey && e.key === "a") {
    return;
  }
   if (e.ctrlKey && e.key === "x") {
    return;
  }


  const allowedKeys = ['control', 'Backspace', 'Delete', 'End', 'Home', 'Tab', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', ',', '.', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

  if (allowedKeys.indexOf(e.key) != -1) {
    return;
  } else {
    e.preventDefault();
    return false;
  }

}

function replaceCurrencyDotForComma() {
  //Remove if starting with, or .
  if (this.value.indexOf(',') == 0) {
    this.value = this.value.replace(',', '');
  }
  if (this.value.indexOf('.') == 0) {
    this.value = this.value.replace('.', '');
  }

  if (this.value.indexOf('-') > 0) {
    this.value = this.value.replace('-', '');
  }

  //Replace . with ,			
  this.value = this.value.replace('.', ',');

  //Limit to max 2 decimal position
  // this.value = (this.value.indexOf(",") >= 0) ? (this.value.substr(0, this.value.indexOf(",")) + this.value.substr(this.value.indexOf(","), 3)) : this.value;
}