1

HTML

<input type="number" required="" pattern="\d*" id="mobile">

jQuery

var letters = /^[0-9]+$/;
var mobile_backup="";
$(document).ready(function(){
    $("#mobile").on("input", function(){
        var mobile_value=$(this).val();
        if(mobile_value==="")
        {
            mobile_backup=mobile_value;
        }
        else if(mobile_value.match(letters)===null){
            $(this).val(mobile_backup);
        }
        else{
            mobile_backup=mobile_value;
        }
    });
});

Current solution works in all devices (desktop, mobile, tablet). Is there any efficient approach available such that it works in all devices?

I know I can use a pattern for number. But I don't want an alert. I just want to allow the numbers without a dot.

Akash
  • 67
  • 1
  • 5

2 Answers2

2

Use pattern attribute to add regex expression in html tag. Try below code:

<form action="home_page.php">
    <label for="roll_no">Roll Number:</label>
    <input type="number" id="roll" name="roll" pattern="^[\d]+$"  title="Write your roll number"><br><br>
    <input type="submit">
</form>

Note :

  1. The pattern attribute of the input tag is not supported in Safari 10 (or earlier).
  2. Validation of pattern attribute will not prevent from writing in the field but it will prevent from submitting form.
Piyali Das
  • 80
  • 5
0

try step="any" This allows a decimal point

Arghya Sadhu
  • 41,002
  • 9
  • 78
  • 107