[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.
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, ''));
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.