This is a dependency-free easy-to-use vanilla JavaScript addon allowing you to create HTML currency inputs with various different currencies and formattings.

Overview

intl-currency-input

This is a dependency-free easy-to-use vanilla JavaScript addon allowing you to create HTML currency inputs with various different currencies and formats. It doesn't require any additional markup or stylesheets. Check out this CodePen to try it out!

Installation

First you need to include the plugin in your project. There are various ways you can do this.

Download

You can download the package from github right here. After you placed the file in your project, just add a reference to your HTML page.

<script src="path-to-file/intl-currency-input.min.js"></script>

CDN

You can also use jsDelivr to use the script externally. For production it is recommended to specify a version number.

<script src="https://cdn.jsdelivr.net/gh/konstantin-lukas/intl-currency-input/intl-currency-input.min.js"></script>

NPM

If you are working with Node perhaps you want to consider downloading the NPM package instead. Just run this command in your project folder.

npm i intl-currency-input --save

Afterwards you can import it like so.

const { CurrencyInput } = require('intl-currency-input');

Usage

To create a new currency input, first create a simple HTML text input.

<input type="text" name="currency" placeholder="Insert mad bucks">

Create a new object from the CurrencyInput class. Make sure you do this after your HTML and intl-currency-input.min.js have loaded. When creating a currency input you need to pass in your input element as the first parameter. It can be a direct reference to the element or a CSS query. As a second parameter you can pass in an optional options object.

const input = 'input';
const options = {
    currency: 'EUR',
    locale: 'de'
    //Options can be partially or completely omitted.
}
const cinput = new CurrencyInput(input, options);

Options

Options get passed in as an object. Each option is a property of the options object. Below you can find all of the options.

currency

This is an ISO 4217 currency code string. It determines the currency symbol and name as well as how many decimal places to allow. By default this value is set to USD.

currency: 'EUR' //This will give us euros instead of dollars.

locale

This is a two character language locale string which can optionally be followed by a region separated with a hyphen. This automatically determines most of the formatting. The default value is 'en-US'. Sometimes adding a region can make a difference. For instance, 'zh-HK' returns 日圓 for the name of Japanese Yen whereas 'zh-CN' or just 'zh' would return 日元.

locale: 'fr' //This will give us fancy French formatting and names: '1 000,99 yen japonais'.

currencyDisplay

This string value determines how to display the currency. Possible values are 'symbol' (this is default), 'name', 'code', and 'none'. The position of the currency symbol or code is determined by the locale. The name is always display afterwards.

currencyDisplay: 'name' //This will give us 'Euro' instead of '€'.

currencyDisplayFallback

This works essentially the same way as currencyDisplay, but it is only used when currencyDisplay is set to 'symbol', but a symbol couldn't be found. Possible values are 'name', 'code', or 'none'.

currencyDisplayFallback: 'name' //For 'DKK' there is no symbol, so we get: '99 Danish Krone'.

min

This number represents the lowest value a user is allowed to enter. If you want to prevent input of negative number, set this value to 0. There is a hard limit here: -999999999999999 for 0 decimal place currencies, -9999999999999,99 for two decimal place currencies and -999999999999,999 for three decimal currencies. Avoid numbers smaller than that.

min: -10 //-10 is still a valid value. Anything below that and further input would be prevented.

max

This number represents the highest value a user is allowed to enter. This value has to be higher or equal to min. There is a hard limit here: 999999999999999 for 0 decimal place currencies, 9999999999999,99 for two decimal place currencies and 999999999999,999 for three decimal currencies. Avoid numbers bigger than that.

max: 10 //10 is still a valid value. Anything beyond that and further input would be prevented.

defaultValue

This is the number value to have inside the input by default. Make sure this value is within your min and max boundaries. If omitted the input will just stay empty on initialization.

defaultValue: 0 //This would put 0 inside the input instead of showing the input placeholder.

separationCharacter

This string is the character to be used for grouping larger numbers. The default for this value is determined by the locale. Use this property if you want to overwrite the default value. If you don't want to group larger numbers, use '' (an empty string) as value.

separationCharacter: ' ' //This will turn 1,000,000 into 1 000 000.

decimalCharacter

This character separates the decimal places. The default for this value is determined by the locale. Use this property if you want to overwrite the default value. For currencies like the Korean Won this value is redundant as there are no decimal numbers i.e. no minor units. Make sure you pick a symbol that is different from the separation character.

decimalCharacter: ',' //This will turn 99.99 into 99,99.

disableCents

This is a boolean value which is set to false by default. If set to true it will prevent the user from inputting decimal numbers. You don't need to explicitly set this value for languages like Japanese Yen which don't have minor units. The amount of decimal places is automatically determined.

disableCents: true //This will prevent the user from inputting 99,99 put allow 99.

preventInputFromIME

This is a boolean value which is set to true by default. This prevents input method editors (e.g. for the Japanese language) to make any potentially bad input. If you don't know what this is, better leave it as default.

preventInputFromIME: false //This will allow all kinds of crazy input like 'お金大好き♡'.

validCallback

This is a function to call when the user makes a correct input.

validCallback: function () { //This will execute whenever the user makes a correct input.
    console.log('That\'s a valid input.');
}

invalidCallback

This is a function to call when the user makes an incorrect input.

invalidCallback: function () { //This will execute for instance when trying to enter a letter.
    console.log('That\'s not a valid input.');
}

Methods

Not all methods are listed here. Some are just for internal logic.

getValueAsString()

This method will get you whatever is currently visible inside the input.

cinput.getValueAsString(); // returns a string value like '$99.99'

getValueAsFloat()

This method will parse the current input value and give you a float.

cinput.getValueAsFloat(); // returns a number value like 99.99

getValueAsInt()

This method will parse the current input value into the minor unit (i.e. cents) and return an integer. This is very useful if you are doing calculations with this value.

cinput.getValueAsInt(); // returns an integer value like 9999

reinit(options)

Use this function if you need to change any of the settings. This takes an options object as an optional parameter just like the constructor method. If you omit the options, everything will be set to default. In case you need to change the html target element, just create a new instance of CurrencyInput.

cinput.reinit({ //This would display '10,000 日本円' by default.
    currency: 'JPY',
    locale: 'ja',
    currencyDisplay: 'name',
    defaultValue: 10000
});

getCurrencyDecimalCount()

This method will return an integer representing the amount of decimal places the current currency has. For 'JPY' this would be 0, for 'USD' or 'EUR' this would be 2, and for 'TND' it would be 3.

cinput.getCurrencyDecimalCount(); //return value is 0, 2, or 3

getSeparationCharacter(getOriginal)

This method will return the separation character currently used as a string. If you set a custom character it will return that, otherwise the return value will depend on the locale you set. The parameter getOriginal is optional and if set to true, will make the function always return the locale based value and never the one set by the user.

cinput.getSeparationCharacter();

getDecimalCharacter(getOriginal)

This method will return the decimal character currently used as a string. If you set a custom character it will return that, otherwise the return value will depend on the locale you set. The parameter getOriginal is optional and if set to true, will make the function always return the locale based value and never the one set by the user.

cinput.getDecimalCharacter();
You might also like...

The frontend of a full stack application of a personal wallet made with React, Node and MongoDB that allows you to add inputs, outputs and see all your extract.

The frontend of a full stack application of a personal wallet made with React, Node and MongoDB that allows you to add inputs, outputs and see all your extract.

The frontend of a full stack application of a personal wallet made with React, Node and MongoDB that allows you to add inputs, outputs and see all your extract.

Jun 2, 2022

The backend of a full stack application of a personal wallet made with React, Node and MongoDB that allows you to add inputs, outputs and see all your extract.

The backend of a full stack application of a personal wallet made with React, Node and MongoDB that allows you to add inputs, outputs and see all your extract.

My first full stack application with the concept of a personal wallet that allows you to create a personal account to keep track of your entire statement by adding incoming and outgoing transactions, as well as calculating the total balance and being able to edit and delete old transactions.

Jun 23, 2022

The JavaScript currency converter plugin

The JavaScript currency converter plugin

currencyConverter - javascript currency converter Compatibility IE9 and up, Edge, iOS Safari 6+, Chrome 8+, Firefox 6+ Usage The currencyConverter Ins

Nov 26, 2022

This project will be using various AI and Rule Engine algorithm to detect various attack against a company!

This project will be using various AI and Rule Engine algorithm to detect various attack against a company!

📌 Introduction This project will be using various AI and Rule Engine algorithm to detect various attack against a website! 📌 Mission After starting

Apr 29, 2022

Node WebStation is a powerful tool designed for developers allowing them to create advanced web sockets for any use all without having the requirement to code.

Node WebStation Node WebStation is a powerful tool designed for developers to use to create an advanced WebStation for any use all without not having

Jun 4, 2022

This is a boilerplate for creating your own languages for various use cases. You can even create your own programming language from scratch!

Bootstrap compiler This is a bootstrap compiler that can be used to compile to compiler written in the target language. You can write a compiler in th

Nov 14, 2022

Crypto-tracker - Get crypto currency data in one click. Followed by a few more clicks.

https://crypto-tracker-ayaanzaveri08.vercel.app/ Crypto Tracker Crypto Tracker tracks crypto with the CoinGecko API. This app uses the React framework

Apr 30, 2022

🚀 Get 3000+ crypto currency information. Decimals, descriptions, website, contract ane etc...!

Crypto currency data information Description 🚀 Get 3000+ crypto currency information. Decimals, descriptions, website, contract ane etc...! Install n

Aug 14, 2022

Digispark Overmaster : free IDE TOOL allows to create and edit Digispark Scripts by the drag and drop technique,with cool GUI and easy to use it

Digispark Overmaster : free IDE TOOL allows to create and edit Digispark Scripts by the drag and drop technique,with cool GUI and easy to use it

Digispark_Overmaster Digispark Overmaster : free IDE TOOL allows to create and edit Digispark Scripts by the drag and drop technique,with cool GUI and

Nov 14, 2022
Comments
  • Currency with multiple symbols won't adjust cursor properly

    Currency with multiple symbols won't adjust cursor properly

    Hi!

    I've noticed that using currencies that contain more than one symbol (such as BRL - R$) this component will not adjust the caret correctly.

    Reproducing:

    1. Open your codepen https://codepen.io/konstantin-lukas/pen/oNWzwOP
    2. Add "currency: 'BRL'" to the options
    3. Clear the text field
    4. Start typing numbers

    You'll see that the caret will be at this position:

    image

    bug 
    opened by LeoColman 2
  • Fix warning (and error in some browsers):

    Fix warning (and error in some browsers): "event" is deprecated

    The event property of the global object (typically window on the Web) was initially added by Microsoft in Internet Explorer. As it often happens, it then gradually found its way into other popular Web browsers and stayed there becoming another de-facto "standard" -- that is, without being formally specified by any actual authority at the time.

    opened by danilomartinelli 0
  • Library not working in Safari

    Library not working in Safari

    Hi. The library works great in Firefox and Chrome. I have not been experiencing any problems outside of Safari both on macOS (Mojave 10.14.6) and iOS 13. Basically the text input wont display as expected, with the seperators and currency symbols.

    The console logs this error: TypeError: Failed to initialize NumberFormat since used feature is not supported in the linked ICU version ` Any idea wether if this can be solved with a polyfill or a part of the library should be rewritten?

    Remark: I am using Safari version 14.1.2 on the mac.

    bug 
    opened by wwwonka 5
Owner
null
Fast and lightweight dependency-free vanilla JavaScript polyfill for native lazy loading / the awesome loading='lazy'-attribute.

loading="lazy" attribute polyfill Fast and lightweight vanilla JavaScript polyfill for native lazy loading, meaning the behaviour to load elements rig

Maximilian Franzke 571 Dec 30, 2022
Awesome books is a vanilla Javascript which offers CRUD functionalities allowing you to add, remove edit boks info and store it to the local storage.

Awesome Books Awesome books is a simple project that displays new books when a user updates them. Built With HTML-5 CSS3 Javacript Linters Live Demo L

Nemwel Boniface 23 Aug 6, 2022
An obsidian plugin allowing you to register and view different file extensions in a modular manner.

Obsidian Custom File Extensions Plugin This is a plugin for Obsidian to allow associaton of file type extensions with different in-app views via setti

null 5 Dec 6, 2022
Deno module to convert fiat currencies with fetched API from fixer.io

Usage example Deno module to convert fiat money currencies with initial fetched API from fixer.io There are two different modes for this module. Mode

Michel M. 6 Jan 29, 2022
A dependency-free Vanilla JS Accordion Menu Nested

?? A dependency-free Vanilla JS Accordion Menu Nested No dependencies, no automation build tools. Copy/paste and ready to use. CSS and JS are inlined

Tomasz Bujnowicz 4 Dec 18, 2022
Storybook Addon Root Attributes to switch html, body or some element attributes (multiple) at runtime for you story

Storybook Addon Root Attributes What is this This project was inspired by le0pard/storybook-addon-root-attribute The existing library received only on

정현수 5 Sep 6, 2022
Tiny JavaScript library (1kB) by CurrencyRate.today, providing simple way and advanced number, money and currency formatting and removes all formatting/cruft and returns the raw float value.

Zero dependency tiny JavaScript library (1kB bytes) by CurrencyRate.today, providing simple way and advanced number, money and currency formatting and removes all formatting/cruft and returns the raw float value.

Yurii De 11 Nov 8, 2022
Specify various templates for different directories and create them with one click. 🤩

English | 简体中文 Gold Right Specify various templates for different directories and create them with one click. Reason Usually there is something in the

赵東澔 16 Aug 8, 2022
a lightweight, dependency-free JavaScript plugin which makes a HTML table interactive

JSTable The JSTable is a lightweight, dependency-free JavaScript plugin which makes a HTML table interactive. The plugin is similar to the jQuery data

null 63 Oct 20, 2022
The JSTable is a lightweight, dependency-free JavaScript plugin which makes a HTML table interactive

The JSTable is a lightweight, dependency-free JavaScript plugin which makes a HTML table interactive. The plugin is similar to the jQuery data

null 63 Oct 20, 2022