Skip to content

Instantly share code, notes, and snippets.

@sidisinsane
Last active March 3, 2020 20:49
Show Gist options
  • Save sidisinsane/509c6c72216830b6b4a2c34777b4e09d to your computer and use it in GitHub Desktop.
Save sidisinsane/509c6c72216830b6b4a2c34777b4e09d to your computer and use it in GitHub Desktop.
/**
* Format a number while typing it into an input field.
*
* @function formatNumberOnInput
* @param {!Element} element - The input element to format.
*
* @example
*
* formatNumberOnInput(document.getElementById('foo');
*/
function formatNumberOnInput(element) {
element.addEventListener('keyup', function(e) {
var number = parseInt(this.value.replace(/\D/g, ''), 10);
this.value = number.toLocaleString() !== 'NaN' ? number.toLocaleString() : '';
}, false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment