Currency Field for forms

by Ben Clayton

HTML

<input type="text" name="purchase_amount" placeholder='enter amount' />

CSS

input {
  padding: 10px;
  font: 20px Arial;
}

JavaScript

Element.prototype.appendAfter = function(element) {
  element.parentNode.insertBefore(this, element.nextSibling);
}, false;

class make_pretty_currency_input {

  constructor(name, currency) {
    this.hiddenField = document.querySelector('input[name="' + name + '"]');
    this.currencyInput = this.makeNewInputElement(name);
    this.currency = currency || 'GBP'; // https://www.currency-iso.org/dam/downloads/lists/list_one.xml
    this.currencyInput.addEventListener('focus', function(e){this.onFocus(e)}.bind(this));
    this.currencyInput.addEventListener('blur', function(e){this.onBlur(e)}.bind(this));
  }

  makeNewInputElement(name) {

    var newElement = document.createElement('input');
    newElement.type = this.hiddenField.type;
    newElement.name = name + '_pretty';
    newElement.placeholder = this.hiddenField.placeholder;

    /* Adds Element BEFORE NeighborElement */
    newElement.appendAfter(this.hiddenField);
    this.hiddenField.type = "hidden";
    return newElement;
  }

  localStringToNumber(s) {
    return Number(String(s).replace(/[^0-9.-]+/g, ""));
  }

  onFocus(e) {
    e.target.value = this.hiddenField.value
  }

  onBlur(e) {
    const options = {
      maximumFractionDigits: 2,
      currency: this.currency,
      style: "currency",
      currencyDisplay: "symbol"
    }
    this.hiddenField.value = e.target.value
    e.target.value = this.localStringToNumber(e.target.value).toLocaleString(undefined, options);
  }

}

new make_pretty_currency_input('purchase_amount');