javascript - how to add comma in textfield in html web page -
this question has answer here:
i have web page in input data <input />
, 1000 want 1,000 not change id value show becuase using same id in other calculation if 1,000 show nan... how can avoid this?
<input type="text" id="test" onblur="addcommas()"> <script> function addcommas(nstr){ var offset = nstr.length % 3; if (offset == 0) return nstr.substring(0, offset) + nstr.substring(offset).replace(/([0-9]{3})(?=[0-9]+)/g, "$1,"); else return nstr.substring(0, offset) + nstr.substring(offset).replace(/([0-9]{3})/g, ",$1"); } alert(addcommas("1234567")); </script>
i have got code forum... have idea how make function simple shows in input box when id value shows 1000?
test value this :
function isnumber(n) { return !isnan(parsefloat(n)) && isfinite(n); }
it prevent nan's.
and use @pete's link know how print number commas thousands separators in javascript
edit comment : can use <input type="hidden" id="testvalue" />
, store real value in it.
so code :
<input type="text" id="test" onblur="addcommas(this)"> <input type="hidden" id="testrealvalue"> <script> function isnumber(n) { return !isnan(parsefloat(n)) && isfinite(n); } function addcommas(input){ nstr = input.value; if(!isnumber(nstr))return; document.getelementbyid("testrealvalue").value = nstr; var offset = nstr.length % 3; if (offset == 0) input.value = nstr.substring(0, offset) + nstr.substring(offset).replace(/([0-9]{3})(?=[0-9]+)/g, "$1,"); else input.value = nstr.substring(0, offset) + nstr.substring(offset).replace(/([0-9]{3})/g, ",$1"); } </script>
here jsfiddle