如何在 HTML 文本输入字段中仅允许数字输入
可以利用 JavaScript 的 setInputFilter 函数将用户在文本输入字段中的输入限制为数字字符和小数点('.'):
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)) { 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")) { this.classList.add("input-error"); this.setCustomValidity(errMsg); this.reportValidity(); this.value = this.oldValue; this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd); } else { this.value = ""; } }); }); }
要强制数字输入,请使用以下命令过滤器:
setInputFilter(document.getElementById("myTextBox"), function (value) { return /^\d*\.?\d*$/.test(value); });
此过滤器根据正则表达式 ^d*.?d*$ 验证输入,该表达式接受仅包含数字、小数点或两者组合的字符串。
以上是如何将 HTML 文本输入限制为仅限数字值?的详细内容。更多信息请关注PHP中文网其他相关文章!