iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 22
0
Modern Web

從Stack Overflow學前端系列 第 22

從StackOverflow上學CODING(22) 使input只接收數字類型的輸入

  • 分享至 

  • xImage
  •  

HTML text input allow only numeric input

Is there a quick way to set an HTML text input () to only allow numeric keystrokes (plus '.')?
有比較快速的方式可以讓 HTML的 text input()只允許數字類型進入嗎?


JavaScript
The setInputFilter function below allows you to use any kind of input filter on a text , including various numeric filters (see below).
Unlike most other solutions, this correctly supports Copy+Paste, Drag+Drop, all keyboard shortcuts, all context menu operations, all non-typeable keys (e.g. cursor and navigation keys), the caret position, all keyboard layouts of all languages and platforms, and all browsers since IE 9.

下面的setInputFilter函式可以讓你在text上用各種的過濾方式,包括各種數字過濾(參考以下)
不像其他的解答,這可以正確的支援複製貼上、拖拉放置或任何的鍵盤快捷鍵、任何有內容的選單動作,任何沒有輸入內容的案件(方向鍵等)

// Restricts input for the given textbox to the given inputFilter.
function setInputFilter(textbox, inputFilter) {
  ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) {
    textbox.addEventListener(event, function() {
      if (inputFilter(this.value)) {
        this.oldValue = this.value;
        this.oldSelectionStart = this.selectionStart;
        this.oldSelectionEnd = this.selectionEnd;
      } else if (this.hasOwnProperty("oldValue")) {
        this.value = this.oldValue;
        this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
      }
    });
  });
}

// Restrict input to digits and '.' by using a regular expression filter.
setInputFilter(document.getElementById("myTextBox"), function(value) {
  return /^\d*\.?\d*$/.test(value);
});

Some input filters you might want to use:
以下列出一些你可能會想用的過濾方式:

Integer values (positive only):
整數值(正數)
/^\d*$/.test(value)

Integer values (positive and up to a particular limit):
整數值(正數且設限制在某個數值)
/^\d*$/.test(value) && (value === "" || parseInt(value) <= 500)

Integer values (both positive and negative):
整數值(正負數)
/^-?\d*$/.test(value)

Floating point values (allowing both . and , as decimal separator):
小數點數值(.或,都可接受)
/^-?\d*[.,]?\d*$/.test(value)

Currency values (i.e. at most two decimal places):
錢號值(最多十進位)
/^-?\d*[.,]?\d{0,2}$/.test(value)

A-Z only (i.e. basic Latin letters):
只允許A-Z字串
/^[a-z]*$/i.test(value)

Latin letters only (i.e. English and most European languages, see https://unicode-table.com for details about Unicode character ranges):
拉丁字母(英文或歐洲個語言)
/^[a-z\u00c0-\u024f]*$/i.test(value)

Hexadecimal values:
十六進位值:
/^[0-9a-f]*$/i.test(value)

Note that you still must do server side validation!
注意到你仍必須要兼顧到伺服器的驗證問題

jQuery
There is also a jQuery version of this. See this answer or try it yourself on JSFiddle.
這個方式也有jQuery的解答詳情請見JSFiddle

HTML 5
HTML 5 has a native solution with (see the specification), but note that browser support varies:
HTML5也有原生的解答不過要注意不是每個瀏覽器都支持:

Most browsers will only validate the input when submitting the form, and not when typing.
Most mobile browsers don't support the step, min and max attributes.
Chrome (version 71.0.3578.98) still allows the user to enter the characters e and E into the field. Also see this question.
Firefox (version 64.0) and Edge (EdgeHTML version 17.17134) still allow the user to enter any text into the field.
大多數的瀏覽器都只允許input上傳一個form,而且不能再正在打字的時候.
大部分的手機瀏覽器也不支持這招


上一篇
從StackOverflow上學CODING(21) JS刪除child元素
下一篇
從StackOverflow上學CODING(23) 如何用 JS刪除所有 CSS Class
系列文
從Stack Overflow學前端30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言