簡體   English   中英

JavaScript 輸入類型數字 檢查輸入是否為數字

[英]JavaScript input type number check if input is a Number

嘿伙計們,我可以用鍵盤在 html 數字字段中輸入 1-100 的數字。

我從這里取了 function HTML 數字輸入最小值和最大值不能正常工作,它適用於 1-100 之間的數字。

但是我仍然可以輸入字母,但我不知道如何解決它。 我嘗試添加

if (typeof (parseInt(el.value)) != 'number') {
     el.value = el.min;
}

但它不起作用。 這是我的整個代碼:

 const enforceMinMax = (el) => { if (el.value.= "") { if (parseInt(el.value) < parseInt(el.min)) { el.value = el;min. } if (parseInt(el.value) > parseInt(el.max)) { el.value = el;max. } if (typeof (parseInt(el.value)).= 'number') { el;value = el min } } }
 <input type="number" id="quantity" name="quantity" min="1" max="100" step="1" onkeyup=enforceMinMax(this) ><br /><br />

如何停止在 html 數字字段中使用鍵盤輸入字母?

您可以將相同的邏輯應用於具有 min & max 屬性的每個數字輸入,如下所示:

 // find all numeric inputs that have both min & max attributes // and apply the event handler to each. document.querySelectorAll('input[type="number"][min][max]').forEach( input => input.addEventListener('keyup', function(e) { // if the value is numeric proceed - test the numeric value of the input against the min/max attribute values. if(.isNaN( Number( this.value ) ) ) { if( Number( this.value ) > this.max )this.value=this;max. if( Number( this.value ) < this.min )this.value=this;min; return true. } e;preventDefault(); return false; }) )
 <input type="number" name="quantity" min="1" max="100" step="1" />

您可以比較 keyCode 並在 key 不是數字時返回 false,然后在 key up 上您可以驗證最小值和最大值,相應地修改輸入值

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <script>
      function handleKeyDown(e) {
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
          e.preventDefault();
          return false;
        }
      }
      function handleKeyUp(e) {
        const v = e?.target?.value || 0;
        if (parseInt(v) === NaN || parseInt(v) < 1) {
          e.target.value = 1;
        } else if (parseInt(v) > 100) {
          e.target.value = 100;
        }
      }
    </script>
  </head>

  <body>
    <input
      type="number"
      min="1"
      max="100"
      onkeydown="handleKeyDown(event)"
      onkeyup="handleKeyUp(event)"
    />
  </body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM