How to add Comma separated Thousands to Number Input?
-
I’d like to add comma separated thousands to number input tag in hybrid app.
How can i implement it?
-
@wann2 The best way in my experience is to use localString. Here are some examples:
var number = 1557564534; number.toLocaleString();
There are options for currency:
var number = 1234567.22 number.toLocaleString("en-US",{style:"currency", currency:"USD"});
All the options can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
-
@munsterlander said:
.toLocaleString()
Thanks a lot for information. It is helpful.
May I ask you one more thing?
I’d like to implement the comma separated thousands when I input numbers inside INPUT tag or after input numbers.
In web, i used keyup or blur event, but in hybrid it doesn;t work.
-
@wann2 I am making an example:
function formatValue(){ var x = Number(document.getElementById('myText').value); document.getElementById('myText2').value = x.toLocaleString(); } <input type="text" id="myText" oninput="formatValue()" /> <input type="text" id="myText2" />
This works, but if you are changing it on the same input as a person is typing, it throws an error due to the non-numeric characters. You would need to remove those items first or change the event to something like onblur.
function formatValue(){ var x = Number(document.getElementById('myText').value); document.getElementById('myText').value = x.toLocaleString(); } <input type="text" id="myText" onblur="formatValue()" />
Either way, in the start of the function there definitely should be a sanitizing component to strip non-numeric characters.
-
Wonderful! It works. Thanks a lot.