How to Restrict an HTML Text Input to Only Allow Numeric Input
To implement numeric-only input in an HTML text input field, you can utilize the JavaScript setInputFilter function. This function comprehensively filters input values by supporting:
JavaScript Code:
// Restricts input for the given textbox to the given inputFilter function. function setInputFilter(textbox, inputFilter, errMsg) { ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout"].forEach(function(event) { textbox.addEventListener(event, function(e) { if (inputFilter(this.value)) { // Accepted value. if (["keydown", "mousedown", "focusout"].indexOf(e.type) >= 0) { this.classList.remove("input-error"); this.setCustomValidity(""); } this.oldValue = this.value; this.oldSelectionStart = this.selectionStart; this.oldSelectionEnd = this.selectionEnd; } else if (this.hasOwnProperty("oldValue")) { // Rejected value: restore the previous one. this.classList.add("input-error"); this.setCustomValidity(errMsg); this.reportValidity(); this.value = this.oldValue; this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd); } else { // Rejected value: nothing to restore. this.value = ""; } }); }); }
Using the Function:
setInputFilter(document.getElementById("myTextBox"), function(value) { return /^\d*\.?\d*$/.test(value); // Allow digits and '.' only, using a RegExp. }, "Only digits and '.' are allowed");
In this example, the setInputFilter function is used on the "myTextBox" element to allow only numeric values. The inputFilter function uses a regular expression to ensure that the input consists solely of digits or a decimal point.
Important Notes:
The above is the detailed content of How to Restrict HTML Text Input to Only Accept Numeric Values Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!