I am working on a financial web application targeted at an Indian audience, and I need to allow users to enter monetary amounts in input fields that automatically format the numbers into Indian numeration style (e.g., "1,00,000" for one lakh). The goal is to have the input field format the number dynamically as the user types, reflecting commas according to Indian numbering system (lakhs and crores).
I've tried using basic JavaScript to manipulate the input value, but I'm encountering issues with cursor positioning and handling backspaces that make the input erratic. Here's the basic code I've been experimenting with:
document.getElementById('myInput').addEventListener('input', function (e) {
var x = e.target.value.replace(/,/g, '');
x = x.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
e.target.value = x;
});
This script does not handle cursor positions well, especially when deleting characters, and it can reset the cursor to the end of the line, which is not user-friendly.
How can I improve this script to handle cursor positions intelligently while maintaining the Indian numeration format? Are there any libraries or plugins that can simplify this functionality? Any help or pointers towards solving this would be greatly appreciated!