JavaScript > Events

OnSubmit in JavaScript

How to execute a JavaScript function when HTML form is submitted?


In case we want to execute a function when the html form is being submitted, we can follow this approach.

<form action="Alert.htm" method="post" onsubmit="return CallFunction()">
        Enter your name:
        <input type="text" name="txtName" id="txtName" />
        <input type="submit" id="btn" name="btn" value="Submit" />
        
        <script>
            function CallFunction() {
                if (document.getElementById("txtName").value == "itfunda") {
                    return true;
                }
                else {
                    alert("Write \"itfunda\" in the textbox");
                    return false;
                }
            }
        </script>
    </form>

In the above code, we have a textbox and a button in the html form. In the Form we have written onsubmit event that executes when the form submitted to the server. On the onsubmit event we are calling “CallFunction” function.

In this function, we are checking for the textbox value, if it is “itfunda” then we are returning true otherwise false. As in the onsubmit event we have written “return CallFunction()” so in case this function returns true and the form is submitted to the server otherwise it is not.

OUTPUT

 Views: 1135 | Post Order: 35



Write for us