Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Textbox numeric with still character e input and negative integers with javascript

I have a textbox with numeric inputs. Here is my javascript set to numeric textbox. But when I try to input letters, "e" is allowed. Problem: What I want to do is no letter should be allowed, only numeric numbers and no negative integer.

HTML:

<input type="numeric" id="usrid" name="usrid" placeholder="Enter number">

Javascript:

$(document).ready(function() {
    $("#usrid").numeric();
});
like image 700
GeekUp Avatar asked Dec 06 '25 07:12

GeekUp


1 Answers

You can use the type="number" and min=0 attributes in your input to enforce validation on these fields:

<input type="number" id="usrid" name="usrid" min=0 placeholder="Enter number">

However, this won't prevent input of negative or non-numeric characters into the input field. For that you'll need to bind a javascript event:

$('#usrid').bind('keypress', function (event) {
    var regex = new RegExp("^[0-9]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
       event.preventDefault();
       return false;
    }
});
like image 99
Anthony E Avatar answered Dec 07 '25 21:12

Anthony E



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!