Enhanced Numeric Input for Alpine.js: Simplifying Number Formatting and Currency Handling.
Enhanced Numeric Input for Alpine.js: Simplifying Number Formatting and Currency Handling.
``html
defer
src="https://unpkg.com/alpinejs-number@latest/dist/number.min.js"
>
`
`shell
yarn add -D alpinejs-number
npm install -D alpinejs-number
`
`js
import Alpine from "alpinejs";
import number from "alpinejs-number";
Alpine.plugin(number);
Alpine.start();
`
Use x-number directive on an input to auto format the number.
`js`
Precision can be set with a with a number modifier.
`js`
The expression between quotes is the prefix.
Note: numbers, minus and decimal point cannot be used in the prefix.
`js`
The thousands separator and the decimal point can be specified in the string between quotes. Simply separate the strings with a vertical bar. The first string is the prefix, the second is the thousands separator, and the third is the decimal point.
`js`
A suffix can be specified within the quotes too. It is the fourth string in the list.
`js`
A suffix can also be added with a string after a colon.
Note: special characters and uppercase characters cannot be used here.
`js`
Use the unsigned modifier to disable negative numbers.
`js`
$toNumber magic can be used to convert a number string to a number.
$toFormatted magic can be used to convert a number to a formatted number string.
`js`
The prefix, thousands separator, decimal character, precision and suffix can be passed as arguments to the function.
`js`
Alpine JS along with the magics can be utilized to transform inputs to numbers before submitting a form.
` js
class="bg-gray-100 p-4 rounded-lg"
>
``