Demo
<input value="100000000" id="testInput" />
Just apply this .formatInput(numberOfCharactersForSeparator, Separator ); to your entrance
$(document).ready(function() { $("#testInput").formatInput(3,"," ); });
using this plugin i just made: p
$.fn.formatInput = (function(afterHowManyCharacter,commaType) { if(afterHowManyCharacter && commaType != ".") { var str = $(this).val(); var comma = commaType != undefined ? commaType : "," ; var strMod ; if($(this).val().indexOf(".") == -1) strMod = replaceAll(comma,"",$(this).val()); else { strMod = replaceAll(comma,"",$(this).val()); strMod = strMod.substring(0,strMod.indexOf(".")); } if($(this).val().indexOf(".") != -1) $(this).val(splitByLength(strMod,afterHowManyCharacter).join( comma )+ $(this).val().substring($(this).val().indexOf("."))); else $(this).val(splitByLength(strMod,afterHowManyCharacter).join( comma )); var nowPos = 0; $(this).on("keyup",function(e) { nowPos = doGetCaretPosition($(this)[0]); var codePressed = e.which ; if(" 8 37 38 39 40 46 17".indexOf(" "+codePressed) == -1 && !e.ctrlKey) { if($(this).val().length >afterHowManyCharacter) { strMod ; if($(this).val().indexOf(".") == -1) strMod = replaceAll(comma,"",$(this).val()); else { strMod = replaceAll(comma,"",$(this).val()); strMod = strMod.substring(0,strMod.indexOf(".")); } if($(this).val().indexOf(".") != -1) $(this).val(splitByLength(strMod,afterHowManyCharacter).join( comma )+ $(this).val().substring($(this).val().indexOf("."))); else $(this).val(splitByLength(strMod,afterHowManyCharacter).join( comma )); if((strMod.length-1)%afterHowManyCharacter == 0) { setCursor($(this)[0],nowPos+1); } else { setCursor($(this)[0],nowPos); } } } }); } else if( commaType == ".") { console.log("You can't use . as Separator"); } function splitByLength(str,maxLength) { var reg = new RegExp(".{1,"+maxLength+"}","g"); ; return reverseStringInArray(str.split("").reverse().join("").match(reg).reverse()); } function replaceAll(find, replace, str) { return str.replace(new RegExp(find, 'g'), replace); } function reverseStringInArray(arr) { $.each(arr,function(i,val) { arr[i] = arr[i].split("").reverse().join(""); }); return arr ; }
source share