Created
January 8, 2025 02:13
-
-
Save Pauloparakleto/e6ded2375aded60ca8532bef45597df0 to your computer and use it in GitHub Desktop.
The Mask, a simple money mask which keeps the cursor in the same relative position
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Money Input Mask</title> | |
<style> | |
input { | |
font-size: 18px; | |
padding: 10px; | |
width: 100px; | |
} | |
</style> | |
</head> | |
<body> | |
<input type="text" id="moneyInput" placeholder="0,00" /> | |
<script> | |
document.getElementById('moneyInput').addEventListener('input', function(e) { | |
let input = e.target; | |
let value = input.value.replace(/\D/g, ''); // Remove non-numeric characters | |
let cursorPosition = input.selectionStart; | |
let oldValueLength = input.value.length; | |
// Update value and cursor position accordingly | |
value = (value / 100).toFixed(2) + ''; // Divide by 100 to get cents and convert to string | |
value = value.replace(".", ","); // Replace decimal point with a comma | |
value = value.replace(/(\d)(?=(\d{3})+\,)/g, '$1.'); // Add thousand separators | |
input.value = value; | |
let newValueLength = input.value.length; | |
// Adjust cursor position to stay in the same relative place | |
cursorPosition = Math.max(cursorPosition + (newValueLength - oldValueLength), 0); | |
input.setSelectionRange(cursorPosition, cursorPosition); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment