I have a text input where I want it to format while typing a value allowing 2 decimal places and 1000 separators. It should only allow digits. I have done the following but
$('#price').on('keyup click change paste input', function (event) {
$(this).val(function (index, value) {
if (value != "") {
//return '$' + value.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
var decimalCount;
value.match(/\./g) === null ? decimalCount = 0 : decimalCount = value.match(/\./g);
if (decimalCount.length > 1) {
value = value.slice(0, -1);
}
var components = value.toString().split(".");
if (components.length === 1)
components[0] = value;
components[0] = components[0].replace(/\D/g, '').replace(/\B(?=(\d{3})+(?!\d))/g, ',');
if (components.length === 2) {
components[1] = components[1].replace(/\D/g, '').replace(/^\d{3}$/, '');
}
if (components.join('.') != '')
return '$' + components.join('.');
else
return '';
}
});
});