How Can I do this With Ajax?
I have input field
If I start writing Number into the input field
Example:
1000000
Turn to this
1,000,000
Automatically!
Look Intl.NumberFormat.
I think it can achieve what you want easily.
Just note it works in IE11+, Chrome & Firefox, and is unavailable in Safari (good job Apple).
Ajax is not required at all. I think you are confused with what AJAX really is. See this tutorial on AJAX. Whatever you are trying to achieve can be done with Regular Expression, like this :
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
var number = numberWithCommas(1000000); //Results 1,000,000
To show this on the screen :
JavaScript :
function myfunc(){
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
document.write(numberWithCommas(document.getElementById("input").value));
}
HTML :
<form>
<input type = "text" id = "input"/>
<button id = "button" onclick = "myfunc()">Go</button>
</form>
See this tutorial for a better understanding of Regular Expression.
I would recommend using the function formatNumber of the accounting.js library.
accounting.formatNumber(9876543.21, 0, ",")
returns 9'876'543
Then you also have more function available for output settings as well as number parsing.
To add Commas You can use this code:
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
To listen ajax request after complete try this:
$(document).ajaxComplete(function () {
addCommas("Some strtings ... 10000000 ");
});