Skip to content

Instantly share code, notes, and snippets.

@rtio
Created June 6, 2018 17:36
Show Gist options
  • Select an option

  • Save rtio/8a4e087a5fe1d57efe77c591cc75fd33 to your computer and use it in GitHub Desktop.

Select an option

Save rtio/8a4e087a5fe1d57efe77c591cc75fd33 to your computer and use it in GitHub Desktop.
mask
<input type='text' id="textBox">
String.prototype.formatTo = function(decimal) {
let digits = this.replace(/\D/g, '');
digits = parseInt(digits).toString();
if (digits.length <= decimal) {
return '00,' + ('0'.repeat(decimal) + digits).slice(-decimal);
}
if (digits.length == (decimal + 1)) {
return '0' + digits.substring(0, 1) + ',' + digits.substring(1, decimal + 2);
}
if (digits.length > decimal) {
return digits.substring(0, 2) + ',' + digits.substring(2, decimal + 2);
}
}
let textBox = document.getElementById("textBox");
textBox.addEventListener("keyup", function(e) {
this.value = this.value.formatTo(5);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment