I have an input field, that only allows numbers and one point.
$('.number').keypress(function(event) {
    var $this = $(this);
    if ((event.which != 46 || $this.val().indexOf('.') != -1) &&
       ((event.which < 48 || event.which > 57) &&
       (event.which != 0 && event.which != 8))) {
           event.preventDefault();
    }
    var text = $(this).val();
    if ((event.which == 46) && (text.indexOf('.') == -1)) {
        setTimeout(function() {
            if ($this.val().substring($this.val().indexOf('.')).length > 3) {
                $this.val($this.val().substring(0, $this.val().indexOf('.') + 3));
            }
        }, 1);
    }
    if ((text.indexOf('.') != -1) &&
        (text.substring(text.indexOf('.')).length > 2) &&
        (event.which != 0 && event.which != 8) &&
        ($(this)[0].selectionStart >= text.length - 2)) {
            event.preventDefault();
    }      
});.number {
    padding: 5px 10px;
    font-size: 16px;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="number" />I want to use this for currency so instead of the point I need to have a comma. So I replaced every point into the function with a comma. But it is not working.
$('.number').keypress(function(event) {
    var $this = $(this);
    if ((event.which != 46 || $this.val().indexOf(',') != -1) &&
       ((event.which < 48 || event.which > 57) &&
       (event.which != 0 && event.which != 8))) {
           event.preventDefault();
    }
    var text = $(this).val();
    if ((event.which == 46) && (text.indexOf(',') == -1)) {
        setTimeout(function() {
            if ($this.val().substring($this.val().indexOf(',')).length > 3) {
                $this.val($this.val().substring(0, $this.val().indexOf(',') + 3));
            }
        }, 1);
    }
    if ((text.indexOf(',') != -1) &&
        (text.substring(text.indexOf(',')).length > 2) &&
        (event.which != 0 && event.which != 8) &&
        ($(this)[0].selectionStart >= text.length - 2)) {
            event.preventDefault();
    }      
});.number {
  padding: 5px 10px;
  font-size: 16px;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="number" /> 
     
    