If you want to allow your users to enter only numeric value in an HTML text input field, you can create a regular expression and test the input value against it using the test() method.
Let's try out the following example which applies a red outline to the text input box if the value entered is not integer or float, applies green outline otherwise:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Allow Only Numeric Input in HTML Text Input Field</title>
<style>
.success{
outline: 2px solid green;
}
.error{
outline: 2px solid red;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
// Define regular expression
var regex = /^\d*[.]?\d*$/;
$("#myInput").on("input", function(){
// Get input value
var inputVal = $(this).val();
// Test input value against regular expression
if(regex.test(inputVal)){
$(this).removeClass("error").addClass("success");
} else{
$(this).removeClass("success").addClass("error");
}
});
});
</script>
</head>
<body>
<input type="text" id="myInput">
<p><strong>Note:</strong> This HTML text input only allow numeric keystrokes and decimal ('.')</p>
</body>
</html>
Note that the input event fires on keyboard input, mouse drag, autofill and even copy-paste. But, it will not fire if you paste the same string or select and retype the same character inside the input.
If you want to allow only numeric characters (0-9) in HTML text input, use the regex /^\d*$/. In the above example if you also want to allow negative values you can use the regex /^-?\d*[.]?\d*$/.
Use the RegExp
test()
MethodIf you want to allow your users to enter only numeric value in an HTML text input field, you can create a regular expression and test the input value against it using the
test()
method.Let's try out the following example which applies a red outline to the text input box if the value entered is not integer or float, applies green outline otherwise:
Note that the input event fires on keyboard input, mouse drag, autofill and even copy-paste. But, it will not fire if you paste the same string or select and retype the same character inside the input.
If you want to allow only numeric characters (0-9) in HTML text input, use the regex /^\d*$/. In the above example if you also want to allow negative values you can use the regex /^-?\d*[.]?\d*$/.
need an explanation for this answer? contact us directly to get an explanation for this answer