Skip to content

Instantly share code, notes, and snippets.

@ambercouch
Last active October 21, 2016 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ambercouch/221a17786e9a848290872a9a99995d69 to your computer and use it in GitHub Desktop.
Save ambercouch/221a17786e9a848290872a9a99995d69 to your computer and use it in GitHub Desktop.
Format number with thousand separator whilst typing
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