如何在 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中文網其他相關文章!