Skip to content

Instantly share code, notes, and snippets.

@trungv0
Last active August 29, 2015 14:26
Show Gist options
  • Save trungv0/4ee4efbca35ee837fd80 to your computer and use it in GitHub Desktop.
Save trungv0/4ee4efbca35ee837fd80 to your computer and use it in GitHub Desktop.
Format HTML input on the fly (require jQuery)
$container.on('keyup', '.auto-formatted', function(e) {
var val = $(this).val();
var pureVal = parseFloat(util.unformat(val));
if (isValid(pureVal)) { // isNaN if number
$(this).data('val', defaultVal); // 0 if number
return;
}
$(this).data('val', pureVal);
var newVal = util.format(pureVal);
// preserve cursor position/selection
var lengthDiff = newVal.length - val.length;
var start = this.selectionStart + lengthDiff,
end = this.selectionEnd + lengthDiff;
$(this).val(newVal);
this.setSelectionRange(start, end);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment