JSFiddle - React, Tailwind, and code Playground
HTML
<input type="text" maxlength="10" id="myInput">
JavaScript
var input = document.getElementById("myInput");
function isCaretAtTheStart(el) {
if (typeof el.selectionEnd == "number") {
// Modern browsers
return el.selectionEnd == 0;
} else if (document.selection) {
// IE < 9
var selRange = document.selection.createRange();
if (selRange && selRange.parentElement() == el) {
// Create a working TextRange that lives only in the input
var range = el.createTextRange();
range.moveToBookmark(selRange.getBookmark());
return range.moveEnd("character", -el.value.length) == 0;
}
}
return false;
}
input.onkeypress = function(e) { e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
// Allow non-printable keys
if (!charCode || charCode == 8 /* Backspace */ ) {
return;
}
var typedChar = String.fromCharCode(charCode);
// Allow numeric characters
if (/\d/.test(typedChar)) {
return;
}
// Allow the minus sign (-) if the caret is at the start and there is not already a minus sign
if (typedChar == "-" && isCaretAtTheStart(this) && this.value.charAt(0) != "-") {
return;
}
// In all other cases, suppress the event
return false;
};