You can use regex
in solving this problem, note that your input field should prevent user from typing letter/non-digit character, other than replacing all the typed non-digit characters with empty string, doing that is not professional:
$('input').on('input', 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 n = number.split('').reverse().join("");
var n2 = n.replace(/\d\d\d(?!$)/g, "$&,");
return "$" + n2.split('').reverse().join('');
}
Demo.