如何使用 jQuery 只允許在文字框中輸入數字?


我們可以很容易地使用 jQuery 只允許在文字框中輸入數字。在 keyup() 事件中設定程式碼,只允許數字值,這樣文字框就不會接受字串。我們將看到兩個例子:

  • 使用 jQuery replace() 方法只允許在文字框中輸入數字
  • 使用 jQuery fromCharCode() 方法只允許在文字框中輸入數字

使用 jQuery replace() 方法只允許在文字框中輸入數字

在這個例子中,我們將看到如何使用 jQuery replace() 方法只允許在文字框中輸入數字。我們必須在 keyup 事件中設定程式碼,以便在輸入時只允許數字,否則文字框將不允許輸入字串:

$('.numbers').keyup(function () {
   this.value = this.value.replace(/[^0-9\.]/g,'');
});

上面,我們設定了一個正則表示式,只允許在文字框中輸入 0-9 的數字。.numbers 是為兩個輸入設定的類,即:

<p>Rank: <input type="text" class="numbers" value="" /> </p> <p>Marks: <input type="text" class="numbers" value="" /> </p>

示例

現在讓我們看看使用 jQuery replace() 方法只允許在文字框中輸入數字的完整示例:

<!DOCTYPE html> <html> <title>Input Numbers Only</title> <head> <script src="https://code.jquery.com/jquery-git.js"></script> </head> <body> <h1>Score</h1> <p>Rank: <input type="text" class="numbers" value="" /> </p> <p>Marks: <input type="text" class="numbers" value="" /> </p> <script> $('.numbers').keyup(function () { this.value = this.value.replace(/[^0-9\.]/g,''); }); </script> </body> </html>

輸出

上面的文字框只允許輸入數字。

使用 jQuery fromCharCode() 方法只允許在文字框中輸入數字

在這個例子中,我們將使用 jQuery fromCharCode() 方法只允許在文字框中輸入數字。我們必須在 keypress 事件中設定程式碼,以便在輸入時只允許數字,否則文字框將不允許輸入字串:

$('.numbers').keypress(function (e) {
   if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;
});

上面,我們設定了一個正則表示式,只允許在文字框中輸入 0-9 的數字。.numbers 是為兩個輸入設定的類,即:

<p>Rank: <input type="text" class="numbers" value="" /> </p> <p>Marks: <input type="text" class="numbers" value="" /> </p>

示例

現在讓我們看看只允許在文字框中輸入數字的完整示例:

<!DOCTYPE html> <html> <title>Input Numbers Only</title> <head> <script src="https://code.jquery.com/jquery-git.js"></script> </head> <body> <h1>Score</h1> <p>Rank: <input type="text" class="numbers" value="" /> </p> <p>Marks: <input type="text" class="numbers" value="" /> </p> <script> $('.numbers').keypress(function (e) { if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false; }); </script> </body> </html>

輸出

更新於:2022年11月22日

12K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.