1

How to Allow Only Numeric Value in HTML Text Input Using jQuery

 1 year ago
source link: https://www.laravelcode.com/post/how-to-allow-only-numeric-value-in-html-text-input-using-jquery
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to Allow Only Numeric Value in HTML Text Input Using jQuery

  1398 views

  2 years ago

jQuery

Use the RegExp test() Method

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-1.12.4.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>
Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK