<h2>JavaScript input filter showcase</h2>
<table>
<tr>
<td>Integer</td>
<td><input id="intTextBox" /></td>
</tr>
</table>
<script>
function setInputFilter(textbox, inputFilter) {
[
"input",
"keydown",
"keyup",
"mousedown",
"mouseup",
"select",
"contextmenu",
"drop",
].forEach(function (event) {
textbox.addEventListener(event, function () {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
this.value = "";
}
});
});
}
setInputFilter(document.getElementById("intTextBox"), function (value) {
return /^-?\d*$/.test(value);
});
</script>
Read More: HTML text input allows only numeric input
Top comments (0)