簡體   English   中英

僅表單輸入限制數字

[英]form input restrict number only

我有一個腳本可以將表單輸入設置為僅數字......但它只在桌面上工作。 在移動設備中嘗試時,同樣不起作用。 問題是什么?

<input class="input--style-4" type="text" name="field6" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"required>
<span id="error" style="color: Red; display: none">* Input digits (0 - 9)</span>

這是表單輸入,下面是用於表單的 javascript

<script type="text/javascript">
    var specialKeys = new Array();
    specialKeys.push(8); //Backspace
    function IsNumeric(e) {
        var keyCode = e.which ? e.which : e.keyCode
        var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
        document.getElementById("error").style.display = ret ? "none" : "inline";
        return ret;
    }
</script>

您可以將表單輸入限制為僅允許數字。

 $(document).ready(function () { // Allow number only for html input text $(document).on('keypress', ':input[name="qty"]', function (e) { if (isNaN(e.key)) { return false; } }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="qty" type="text" name="qty" />

將輸入字段更改為 type="number" 而不是 type="text"。

您可以簡單地使用 isNaN() function。 如果值為“非數字”,它將返回。 然后,您可以像這樣編寫代碼:

if(!isNaN(e)){
  //Your code here
}

您可以使用 input type="number" 和一些 CSS 來顯示和隱藏消息。

為了避免之前出現錯誤,您可以添加一個 class。 這不會阻止用戶輸入無效字符。

 span.error { color: red; display: none; } input.hadInput:invalid + span.error { display: block; }
 <input class="input--style-4" type="number" name="field6" oninput="this.classList.add('hadInput')" required> <span class="error">* Input digits (0 - 9)</span>

暫無
暫無

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

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