[Demo] Allow Numbers only in HTML input box and formatting of number with comma separator

This example demonstrates how to allow numbers only and prevent special characters and alphabets in an HTML input box. Also example describes how to format number with comma (,) or any separator. Most important thing is that it works in mobile and desktop both. Important points - 1. Pass first parameter as number string and second parameter (optional) as seperator (e.g. ",") 2. By default, number would be formatted by comma (,) separator.

by Rahul Saraswat

HTML

Input a number : <input id="txtTel" type="tel" onkeyup="allowNumbersOnly(this)"/>

JavaScript

$('#txtTel').off('keyup change paste');
$('#txtTel').on('keyup change paste', function (e) {
	var priceTxtBox = $(this);
	if (priceTxtBox.val()) {
  //Price value formatting with point seperator e.g. 5.555        
  	priceTxtBox.val(formatNumberWithSeperator(priceTxtBox.val()));
	}
});

function formatNumberWithSeperator(nStr){
  //Pass first parameter as number string and second parameter (optional) as seperator (e.g. ",").
  //By default, number would be formatted by comma (,) seperator
	var seperator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ',';
        nStr += '';
        var x = nStr.split('.');
        var x1 = x[0];
				var x3 = "";
				x.forEach(function(num, index){
          if(index!==0)
            x3 += num;
        });
        var x2 = x.length > 1 ? '.' : '';
        var rgx = /(\d+)(\d{3})/;

        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + seperator + '$2');
        }
        x3 = x3.replace(rgx, '$1' + seperator + '$2')
        return x1 + x2 + x3;
}

function allowNumbersOnly(obj) {
  //Use this function onkeyup event to acccept numbers only
  $(obj).val($(obj).val().replace(/[^0-9]/g, ''));
}