Ensure Field Only Allows Numerical Values Before Submission

Introduction

To ensure that users can only enter numerical values into a text field, you can implement a simple script restricting input to numbers. This validation helps maintain data integrity by preventing non-numeric characters from being entered.

How does it work?

The script listens for keypress events on the specified text field and allows only numeric keys (0-9), backspace, and delete. By preventing other keypresses, the script ensures that only numerical values can be entered into the field.

  1. Replace "numeric" with the ID of your text field.
  2. Add the following script to your form's custom HTML section:
    <script>
    $(document).ready(function() {
        $("#numeric").keydown(function(event) {
            // Allow only backspace and delete
            if ( event.keyCode == 46 || event.keyCode == 8 ) {
                // let it happen, don't do anything
            }
            else {
                // Ensure that it is a number and stop the keypress
                if (event.keyCode < 48 || event.keyCode > 57 ) {
                    event.preventDefault();
                }
            }
        });
    });
    </script>

There are several online resources that describe this (e.g., http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jqueryhttp://snipt.net/GerryEng/jquery-making-textfield-only-accept-numeric-values, etc.).

Created by Julieth Last modified by Aadrian on Dec 13, 2024