JSFiddle - React, Tailwind, and code Playground
HTML
<div>
Enter an integer (type="number")<br/>
A)
<input type="number" />
</div>
<div>
Enter an integer (type="text" with JavaScript)<br/>
B)
<input class="number" type="text" pattern="[0-9,$]*" />
</div>
CSS
input[type=text]:invalid { background-color: red; }
div { background-color: #003366; padding: 2em 1em; color: white;
font-size: 120%; font-family: Arial; }
JavaScript
$(document).ready(function(){
// Based off of http://stackoverflow.com/questions/9156390/add-commas-for-a-number-in-input-field-while-typing
function RemoveRougeChar(convertString){
if(convertString.substring(0,1) == ","){
return convertString.substring(1, convertString.length)
}
return convertString;
}
$('input.number')
/* // optional...
.on("keyup",function(e){
// skip for arrow keys
if(e.which >= 37 && e.which <= 40){
e.preventDefault();
}
var $this = $(this);
var num = $this.val().replace(/[^0-9]+/g, '');
$this.val(num);
})*/
.on("focus",function(e){
var $this = $(this);
var num = $this.val().replace(/,/g,"");
$this.val(num);
}).on("blur", function(e){
var $this = $(this);
var num = $this.val().replace(/[^0-9]+/g, '').replace(/,/gi, "").split("").reverse().join("");
var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
$this.val(num2);
});
});