Add data-currency to a text field
so the amount shows in the page's locale and currency once the field loses focus.
The attribute holds an ISO 4217 code, such as EUR, on an
<input> of type text. AutoInit()
starts every one. The locale comes from the nearest lang. While
the field has focus it shows the plain number, such as 1234,5, and
when it loses focus it shows 1.234,50 €. Add
inputmode="decimal" so phones open a number pad with a decimal
key, and name the currency in the label.
<div class="field">
<input id="price" name="price" type="text" inputmode="decimal" autocomplete="off"
placeholder=" " data-currency="EUR">
<label for="price">Price in euros</label>
</div>
How typed amounts read
Typed and pasted text keeps its digits, ., , and a
leading minus, and drops spaces, signs and letters. The last . or
, is the decimal mark when it is followed by no more digits than
the currency shows; every other separator groups. So 1234.5,
1234,5, 1.234,5 and 1,234.50 all read
1234.5, and 1.234 reads 1234 for euros. Yen has no fraction
digits, so every separator groups. Full-width digits from an input method
editor and the locale's own digits read as digits.
The submitted value
The form submits the plain number, 1234.5, rounded as the field
shows it, so a submit and new FormData(form) read the same value,
also when the form is submitted with Enter while the field has focus. The field
keeps its name, and an empty field submits an empty string.
A saved value is formatted when the component starts, without an
input or change event, and again after a form reset.
It reads as a plain number first, so write saved amounts as
value="1234.5"; value="1.234" is 1.234. A value a
script sets shows formatted after the field next loses focus. A page's
change and blur listeners read the formatted text, and
the instance's value property gives the number.
min, max and step do not apply to a text
input. Do not combine data-currency with
data-mask.
Text with no amount
Text with no digit stays as typed, and the field reports itself invalid with
Enter an amount. until it holds an amount or is empty. A
.validate field shows the message when it loses focus.
Options and methods
i18n.invalid replaces the validity message, from script or from
data-currency-input-options.
<input type="text" data-currency="EUR"
data-currency-input-options='{"i18n":{"invalid":"Betrag eingeben."}}'>
const price = Expressive.CurrencyInput.getInstance(document.getElementById('price'));
price.value; // 1234.5, or null when the field is empty or holds no digit
price.destroy(); // removes the listeners, clears the message, leaves the text