如何将 HTML 文本输入限制为仅允许数字输入
要在 HTML 文本输入字段中实现仅数字输入,您可以利用 JavaScript setInputFilter 函数。此功能通过支持以下功能全面过滤输入值:
JavaScript代码:
// 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 = ""; } }); }); }
使用函数:
setInputFilter(document.getElementById("myTextBox"), function(value) { return /^\d*\.?\d*$/.test(value); // Allow digits and '.' only, using a RegExp. }, "Only digits and '.' are allowed");
在此示例中,setInputFilter 函数用于“myTextBox”元素以允许仅数值。 inputFilter 函数使用正则表达式来确保输入仅包含数字或小数点。
重要说明:
以上是如何使用 JavaScript 将 HTML 文本输入限制为仅接受数字值?的详细内容。更多信息请关注PHP中文网其他相关文章!