Asha
Asha

Reputation: 27

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>

Upvotes: 0

Views: 153

Answers (4)

philip
philip

Reputation: 96

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

Upvotes: 0

Joko Wandiro
Joko Wandiro

Reputation: 1987

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

Upvotes: 1

epascarello
epascarello

Reputation: 207501

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>

Upvotes: 0

Shakil Anwar
Shakil Anwar

Reputation: 141

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
}

Upvotes: 0

Related Questions