jeudi 25 novembre 2021

The input from client side should entered only digits, if is alphabets should give an error msg. using HTML, JavaScript

This is the question;

Create an html page with the following form:

Enter your name

Add a js validation function to the form that ensures that you can only add numbers in the textbox If you enter alphabets, you should generate an error message in the given div. -->

I run the requiermtn successfully and I'm giving the error message when it entered alphabets. However, it's giving me the same error message when I enter digits as well. Please kindly show how the function or the window.onload should be implemented. Thank you.

My answer is down below;

<head>

    <meta charset="utf-8">

    <title></title>

</head>

<body>




    <script>

        window.onload = function() {

            let form = document.getElementById('form_ref')

            form.onsubmit = function() {

                let user = form.user.value;

                if(parseInt(user) !== user) {

                    document.querySelector('div').innerHTML = "Error! Please enter digits only!";

                    return false;

                }

                return true;

            }

        }

    </script>

   

    <form id="form_ref" method="post" name="example" action="">

   

        <label for="username">User</label><input type="text" name="user" id="username" required>

        <div id="a"></div>

        <br>

       

   

        <input type="submit" value="Submit Information" id="submit">

    </form>

</body>



Aucun commentaire:

Enregistrer un commentaire