Handling monetary input in web forms can be tricky. You need to ensure users enter data in a consistent format, prevent errors, and provide a smooth, intuitive experience.
Manually parsing and formatting currency values can lead to complex and error-prone code.
Fortunately, jQuery provides a powerful event-driven approach to simplify this process. In this article, we'll explore how to leverage jQuery events to create a robust 'mask money' functionality for form input fields, transforming raw user input into beautifully formatted currency values in real-time.
We'll cover everything from capturing keypresses and handling decimal points to displaying currency symbols and ensuring data integrity, empowering you to build user-friendly and reliable financial forms.
Set Mask Money for all Inputs with the class .mask-money
.
It begins by defining variables formInput and formName to store the CSS selector for the input fields and the form ID, respectively.
Upon page load, it iterates through each input field matching the mask-money class and applies the maskMoney function to format their initial values.
/* Input Selector */
var formClass = '.mask-money';
/* Form ID */
var formID = '#myForm';
Apply Mask Money to the default values of input elements.
$(formClass).each(function() {
$(this).val(maskMoney($(this).val()));
});
It attaches a keyup event listener to the input fields. Whenever a key is released within these fields, it:
$(document).on('keyup', formInput, function () {
let val = $(this).val().replaceAll(/\s/g,'');
$(this).val(maskMoney(val));
});
This function takes a string value as input. If the value is empty, it returns an empty string.
Otherwise, it rounds the numerical value. It then uses a regular expression to add spaces as thousands separators, enhancing readability.
function maskMoney(value) {
if (value === '') {
return '';
} else {
value = Math.round(value);
return (value + '').replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1 ');
}
}
Form Submission Handling (submit event):
It attaches a submit event listener to the form.
When the form is submitted, it iterates through the mask-money input fields and removes all whitespace from their values before submission. This ensures that the raw, unformatted numerical data is sent to the server.
$(formName).on("submit", function(e) {
$(formInput).each(function() {
let val = $(this).val().replaceAll(/\s/g,'');
$(this).val(val);
});
});
If you want to process the input on the server side, remove some of the JS code
// var formName = 'form.cms-form';
/*
$(formName).on("submit", function(e) {
$(formInput).each(function() {
let val = $(this).val().replaceAll(/\s/g,'');
$(this).val(val);
});
});
*/
and add the code to your Controller that processes the form
$price = preg_replace("/[^0-9]/", "", $request->inpu('price'));
<script>
(function() {
/* Input Selector */
var formInput = '.mask-money';
/* Form ID */
var formName = '#myForm';
$(formInput).each(function() {
$(this).val(maskMoney($(this).val()));
});
$(document).on('keyup', formInput, function () {
let val = $(this).val().replaceAll(/\s/g,'');
$(this).val(maskMoney(val));
});
$(formName).on("submit", function(e) {
$(formInput).each(function() {
let val = $(this).val().replaceAll(/\s/g,'');
$(this).val(val);
});
});
function maskMoney(value) {
if (value === '') {
return '';
} else {
value = Math.round(value);
return (value + '').replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1 ');
}
}
});
</script>