Last active
August 29, 2015 14:26
-
-
Save trungv0/4ee4efbca35ee837fd80 to your computer and use it in GitHub Desktop.
Format HTML input on the fly (require jQuery)
This file contains 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
$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