jQuery val() Allow Only Numeric Value in <input>

Introduction

This HTML text input only allow numeric key strokes and decimal ('.').

View in separate window

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Allow Only Numeric Input in HTML Text Input Field</title>
<style>
    .success {// w w  w.  j  a  va  2s  .  c o m
        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(){
    var regex = /^\d*[.]?\d*$/;

    $("#myInput").on("input", function(){
        var inputVal = $(this).val();

        if(regex.test(inputVal)) {
            $(this).removeClass("error").addClass("success");
        } else{
            $(this).removeClass("success").addClass("error");
        }
    });
});
</script>
</head>
<body>
    <input type="text" id="myInput">
    
</body>
</html>

The input event fires on keyboard input, mouse drag, auto fill and copy-paste.

It will not fire if you paste the same string or select and retype the same character.




PreviousNext

Related