Speed up development with full-stack environments for every branch.

Learn More

Allow only numbers in an input using jQuery [form]

Forked from How to use the jQuery UI Slider.

5560 Runs 60758 Views 23414 Copies
Saved

Saved

pg1 45

pg1
published 4 years ago

<!doctype html>
<html>
<head>

    <title>Allow only numbers in an input using jQuery</title>
    
    <style>
        body{
            text-align: center;
            font-family: arial;
        }
   
        .input{
            padding: 3px;
        }
        
    </style>


</head>
<body>

    This input only allows to enter numbers<br />
    <input type="text" value="" class="input" size="30" />

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

    <script>

        //When DOM loaded we attach click event to button
        $(document).ready(function() {
            
            //attach keypress to input
            $('.input').keydown(function(event) {
                // Allow special chars + arrows 
                if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 
                    || event.keyCode == 27 || event.keyCode == 13 
                    || (event.keyCode == 65 && event.ctrlKey === true) 
                    || (event.keyCode >= 35 && event.keyCode <= 39)){
                        return;
                }else {
                    // If it's not a number stop the keypress
                    if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
                        event.preventDefault(); 
                    }   
                }
            });
            
        });

    </script>

</body>
</html>
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).