简体   繁体   中英

form input restrict number only

I have a script to set the form input as number only... but it is working only in desktop. While trying in mobile the same is not working. What is the problem?

<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>

This is the form input and below is the javascript used for the form

<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>

You can restrict form input to allow number only.

 $(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" />

Change the input field to type="number" instead of type="text".

You can simply use isNaN() function. It will return if the value is "Not a Number". You can then write your code like this:

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

You can use input type="number" and some CSS to show and hide the message.

To keep the error from appearing before, you can add a class. This will not prevent the user from typing invalid characters.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM