Last active
October 21, 2016 16:05
-
-
Save ambercouch/221a17786e9a848290872a9a99995d69 to your computer and use it in GitHub Desktop.
Format number with thousand separator whilst typing
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
NWS = { | |
$inputForm : {}, | |
offset: 0, | |
FormLength : 0, | |
FormLengthNew : 0, | |
char: ' ', | |
ku: function(selector, char = ' '){ | |
NWS.$inputForm = $(selector); | |
NWS.char = char; | |
NWS.FormLength = NWS.$inputForm.val().length; | |
NWS.formatNum(); | |
}, | |
formatNum: function(){ | |
var start = NWS.$inputForm[0].selectionStart, | |
end = NWS.$inputForm[0].selectionEnd; | |
NWS.$inputForm.val(NWS.format(NWS.$inputForm.val())); | |
NWS.FormLengthNew = NWS.$inputForm.val().length; | |
NWS.offset = NWS.FormLengthNew - NWS.FormLength; | |
NWS.$inputForm[0].setSelectionRange(start + NWS.offset, end + NWS.offset); | |
}, | |
format: function(value){ | |
return value.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, NWS.char); | |
} | |
} | |
$(document).ready(function(){ | |
$(document).on('keyup', '[name=price_from]', function(){ | |
NWS.ku('[name=price_from]'); | |
}); | |
$(document).on('keyup', '[name=price_to]', function(){ | |
NWS.ku('[name=price_to]'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment