Skip to content

Instantly share code, notes, and snippets.

@olimortimer
Last active December 24, 2015 12:09
Show Gist options
  • Save olimortimer/6795397 to your computer and use it in GitHub Desktop.
Save olimortimer/6795397 to your computer and use it in GitHub Desktop.
JS: Pad number inputs to 2 decimal places
// Used to pad numbers inputs to 2 decimal places
function padNumber($input) {
// Rather than store $(this).val(), it's best to keep checking for changes
// When we move off the input
$input.on('blur', function () {
// Ignore if there's no value
if ($(this).val() === '') return;
// Set attr to text
$(this).attr('type', 'text');
// If we don't have a decimal, pad our value with .00
if ($(this).val().indexOf('.') === -1) {
$(this).val($(this).val() + '.00');
}
// Keep padding our value with 0 until we have 2 decimal places
while ($(this).val().indexOf('.') > $(this).val().length - 3) {
$(this).val($(this).val() + '0');
}
// When we focus on the input
}).on('focus', function () {
// Set our attr back to number, so our native number controls return
$(this).attr('type', 'number');
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment