// HTML
<input type='text' id='currency'/>
//JS
$('#currency').keyup(function (e) {
$(this).val(formatCurrency(this.value.replace(/[,$]/g, '')));
}).on('keypress', function (e) {
if (!$.isNumeric(String.fromCharCode(e.which))) e.preventDefault();
}).on('paste', function (e) {
var cb = e.originalEvent.clipboardData || window.clipboardData;
if (!$.isNumeric(cb.getData('text'))) e.preventDefault();
});
function formatCurrency(number) {
var x = number.toString();
var lastThree = x.substring(x.length -
3);
var otherNumbers = x.substring(0, x.length - 3);
if (otherNumbers != '')
lastThree = ',' + lastThree;
return otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") +
lastThree;
}
// Result
1,11,11,111
No comments:
Post a Comment