A step-by-step guide to invoking a function upon submitting a form with an external JavaScript file

How can I execute a function when the user submits a form using an external JavaScript file?

index.html

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

main.js

    function a(){
        alert("Submitting Form");
    }

Answer №1

Use the following code snippet...

This is an HTML file

 <!DOCTYPE html>
 <html>

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

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

 </html>

JavaScript File

 function b() {
    
     alert('hi');
 }

Answer №2

To incorporate external JavaScript files, you can attach an event listener to the onsubmit event of a form and insert the external scripts using the script tag.

For example: how to include an external JS file.

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

Implementation 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">test</h1>
    <form id="form">
      <input
        type="input1"
        class="input1"
        name="verb"
        id="verb"
        placeholder="Verb"
      />
      <button type="submit" >Submit</button>
    </form>

You can define the formSubmitHandler function in the main.js file.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The image is experiencing difficulty loading from the Express static directory

Having some trouble with image loading... I've noticed that images are loading fine from the local folder, but not from the uploads folder which is set to be static. I've been attempting to upload a file from the browser. The upload and save pr ...

Show dynamic outcomes on the site

I'm currently in the process of building a website for a travel search engine and I'm interested in displaying the results in a similar manner to what is done on Hipmunk. https://i.sstatic.net/JWvYo.png Here are some key details: The website ...

Achieving consistent text alignment in HTML and CSS without relying on tables

As I delve into the world of HTML and CSS, I've taken a traditional approach by crafting a login page complete with three input controls (two text inputs and one button). To ensure proper alignment of these elements, I initially turned to the trusty & ...

Using perl ajax to modify a table

In my current Perl script, I am working on a functionality where I retrieve data from an xls file and display it as input text on a webpage. The objective is that when a user selects the edit option from a menu, the entire table fetched from the xls file w ...

Is it possible to make any object reactive within Vuex?

Seeking ways to enhance the sorting of normalized objects based on a relationship. Imagine having an application that requires organizing data in a Vuex store containing multiple normalized objects, like this: state: { worms: { 3: { id: 3, na ...

Is there a way to transfer the getJSON output into an input field?

I am attempting to fill out a form with the data from the most recent entry in my database using $.getJSON. Although the GET request successfully returns the JSON, I am struggling to populate the fields with the data. I am relatively new to this and seekin ...

Unlawful use of the return statement

Can you identify the issue with this code? The browser reports: "Uncaught SyntaxError: Illegal return statement" I'm looking for an explanation in this format: 1 2 3fool 4 5bar 6fool 7 8 9bar... let arr = []; for (i = 0; i <= 100; i++) { if ( ...

Manipulate Browser Navigation Behavior using JavaScript or AngularJS

How to Manage Browser Back Button Behavior Using AngularJS or JavaScript This is not a question, but rather a demonstration of how you can disable and manipulate the behavior of the browser's back button when using AngularJS or plain JavaScript. ...

The problem of Twitter Bootstrap 2 top navigation dropdown not functioning properly on mobile devices

I’ve spent a significant amount of time researching the issue prior to reaching out here, but unfortunately I haven’t been able to find a solution yet. Website Link: Currently, I am using Twitter Bootstrap 2.3.2 and have integrated a form in the drop ...

Here is a unique version of the text: "Implementing a JavaScript function in Angular to activate the data-bs

Attempting to use JavaScript in angular to close/hide a bootstrap5 modal, encountering an issue where the hide function in bootstrap is not working. When manually clicking a button with data-bs-dismiss attribute, it closes the modal as expected, but when t ...

Is using Javascript objects a better alternative to Redux?

I'm in the process of creating my initial application with React and have opted to integrate Redux into it. Since incorporating Redux, it appears that setting a component state to a basic global JavaScript object would be a simpler approach. I unders ...

What is the reason for findUser.username returning as unidentified?

I am encountering an issue where the findUser.username is being printed in my console.log, but the error persists. I would appreciate some assistance with this problem. Thank you. const auth_user = [ { username: "amylussie", password: ...

Determine the width of a dynamically generated div element in JavaScript using the createElement method

Currently, I am utilizing the JavaScript function createElement to generate a new div element and then assigning its innerHTML. Following that action, I am attempting to determine the necessary width required to display the div with all of its content. var ...

When a button is clicked, retrieve information from a server using Node.js

In my front end code, I have a scenario where upon clicking a button, I need to retrieve specific data from the node server to populate a map on the client side. The map can be viewed at: "http://localhost:8080/" Here's how I'm making the reques ...

Combining Multiple NodeLists in Javascript

Initially, I was seeking a sophisticated method to replicate the functionality of Array.concat() on the results of the getElementsByTagName function in older browsers like IE because it appeared that concat wasn't supported. However, as it turns out, ...

Datatables fails to execute page transitions

It seems like I must be missing something, even though my code is quite basic and closely follows the example provided on the web. I am currently using server-side paging. The issue I'm facing is that upon initial page load, the data from the server ...

An issue in Node.js NPM PDFkit arises when generating PDF tables with Voilab pdf table, leading to paragraph errors in the resulting

Greetings everyone, I appreciate you taking the time to visit. I am currently facing some challenges with Voilab PDF Kit, a library for PDFkit that is designed to assist in organizing tables for NPM Pdfkit. After successfully generating a table, I attemp ...

Creating a dynamic multi-item carousel with Materialize (CSS) cards using data from a loop - here's how!

Using a for loop, the following code generates a list of cards. These cards are intended to be displayed in a carousel with 4 cards visible at once, and a next arrow button allows users to navigate through the next set of 4 cards. Materialize cards have ...

Employ a CSS3 media query within a Sass @for loop

Is it really achievable? For instance: @for $i from 1 through 12 { @media screen and (min-width: #{$i * 240}) { width: {$i * 240 + (20*($i-1)) } ; } } However, the issue I'm facing is Invalid CSS after "...nd (min-width: ": expected expre ...

What is the best approach for creating a test that can simulate and manage errors during JSON parsing in a Node.js

My approach to testing involves retrieving JSON data from a file and parsing it in my test.js file. The code snippet below demonstrates how I achieve this: var data; before(function(done) { data = JSON.parse(fs.readFileSync(process.cwd() + '/p ...