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