JavaScript : Accept only a positive integer / float input

To accept only a numeric value ( integer or float ) value in the HTML text field we make use of the following

  • onkeypress : An event occurs when the user presses a key.
  • event.key : The key property of an event returns the identifier of the key that was pressed.
  • isFinite : This function determines if the entered input is a finite number.
  • <string> . indexOf (".") : Checks if a decimal is present in the text field.


Javascript : Program to accept only a decimal / float input.

<!DOCTYPE html>
<html>
<body>
    <script>
        function only_decimal(event) {
            if (event.key === 'Backspace' || event.key === 'Delete'
                || event.key === 'Tab' || event.key === 'Escape'
                || event.key === 'Enter' || event.key === '.'
                || event.key === 'ArrowLeft' || event.key === 'ArrowRight' ||
                isFinite(event.key)) {
                var decimal_str = document.getElementById("id_decimal_field").value;
                if (decimal_str.indexOf(".") != -1 && event.key === '.') {
                    event.preventDefault();
                } else {
                    // Accept the first dot(".")
                    return;
                }
            } else {
                event.preventDefault();
            }
        }

        function DisplayCost() {
            document.getElementById("Cost").innerHTML = "Entered Amount: " + document.getElementById("id_decimal_field").value;
        }
    </script>

    <h2>Accept decimal / float values</h2>

    <label>Enter Cost: </label>
    <input type="text" name="decimal_field" id="id_decimal_field" class="only_decimal" 
            maxlength="20" onkeypress="return only_decimal(event)"/>
    <br><br>
    <button onclick="DisplayCost()">Submit</button>
    <br>
    <p id="Cost"></p>

</body>
</html>

Try it out :
https://jsfiddle.net/algotree/9o1uvt6m/



Copyright (c) 2019-2022, Algotree.org.
All rights reserved.