How to call a function on form submit using external js file

Viewed 382

I want to call a function when the user submit a form, and how to achieve this with external JS script.

index.html

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>teste</title>
            <link rel="stylesheet" type="text/css" href="style.css">
            <link type="text/javascript" src="main.js">
        </head>
            <body>
                <h1 class="title">teste</h1>
                <form action="a()">
                    <input type="input1" class="input1" name="verb" id="verb" placeholder="Verb"/>
                </form>
            </body>
    </html>

main.js

    function a(){
        alert("verb");
    }

2 Answers

You could add event listener on onsubmit event of form and you can add the external scripts by using script tag.

Example: how to add external JS file.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>teste</title>
        <link rel="stylesheet" type="text/css" href="style.css">
        <script src="./main.js"></script>
    </head>
        <body>
           //.. html
        </body>
</html>

Working Example:

let formElem = document.getElementById("form");
formElem.addEventListener("submit", formSubmitHandler);
function formSubmitHandler(event) {
  event.preventDefault();
  console.log("Form submitted");
  console.log("User entered: " + event.target.elements[0].value);
}
<h1 class="title">teste</h1>
    <form id="form">
      <input
        type="input1"
        class="input1"
        name="verb"
        id="verb"
        placeholder="Verb"
      />
      <button type="submit" >Submit</button>
    </form>

You can add the formSubmitHandler in the main.js file.

Follow This code...

HTML file

 <!DOCTYPE html>
 <html>

 <head>
     <meta charset="utf-8">
     <title>teste</title>
     <link rel="stylesheet" type="text/css" href="style.css"> 
 </head>

 <body>
     <h1 class="title">teste</h1>
     <form >
         <input type="text" name="text" id="input" placeholder="Verb" />
         <input type="submit" onclick="a()">
     </form>
     <script src="./index.js"></script>
 </body>

 </html>

JS File

 function a() {
    
     alert('hello');
 }
Related