If you developing an app that has currency input, you may think of how to make it 'prettier' with thousand separator. Developing thousand separator by your own may be hard. Or if you found scripts on a site like Stackoverflow, you may be unsure if it works well or buggy. So, the last options is to find a library for it. I found one and it looks promising but I have bad news, it needs jQuery. But the old ways still worth to use these days, as long as you don't use legacy version of it. Anyway, let's implement it in our beloved framework Laravel and its Mix.
Prerequisites to code along
Have your own Laravel app to follow along, you already installed jQuery with Laravel-Mix and make sure the jQuery is working for your web.
Installing jQuery Mask Plugin
The library works as a plugin for jQuery. To install jQuery mask, here is the npm command:
npm install jquery-mask-plugin --save-dev
The Currency Component
The component to use later is simple, we use <input>
element with text
type (not number
type) and has rupiah
class in it:
<input class="rupiah" type="text" name="price" id="price">
Applying jQuery Mask
As usual, you may have similar entrypoint javascript like this:
window._ = require('lodash');
try {
window.$ = window.jQuery = require('jquery');
} catch (error) {
console.log(error);
}
By the way, I live in Indonesia and the nation's currency is Rupiah (IDR). The example format is Rp15,000,000
, it uses comma to separate the thousands. So the masking for this is 0,000,000,000
and we limit it to billion with maximum up to 9,999,999,999
. Let's import the jquery mask plugin below the jquery object assignation and the masking to the rupiah
class:
window._ = require('lodash');
try {
window.$ = window.jQuery = require('jquery');
require('jquery-mask-plugin');
$('.rupiah').mask('0,000,000,000', {reverse: true});
} catch (error) {
console.log(error);
}
Build and Test!
Run npm run development
for development-mode assets or npm run production
for production-ready assets. The masking for the component should be working, let me know if it doesn't 🎃.
Unmasking Upon Form Submit
If the component is used for a form input and you masked it, the submitted value will be the masked value and to store it in the database of course we need the raw value. To handle this, you can bootstrap any form submission and unmasked the value like this:
$('form').on('submit', function(){
$('.rupiah').unmask();
});
version used:
node v14.16.0
npm 6.14.11
laravel-mix 6.0
Top comments (0)