Having trouble with e.preventDefault() not working on submit() in Javascript?

I'm facing an issue with submitting a form using JavaScript submit()

LIVE ACTION : https://jsfiddle.net/98sm3f3t/

HTML :

<form id="myForm" action="">
    First name: <input type="text" name="fname"><br>
    <button id="myButton" type="button">Submit form</button>
</form>

JS :

document.getElementById("myButton").addEventListener("click", function() {

    document.getElementById("myForm").submit();

});

document.getElementById("myForm").addEventListener("submit", function(e) {

    e.preventDefault();

    alert("cancel submitting");

});

The code should display an alert() and cancel submitting.

Can anyone identify what's causing the issue in my code?

Thank you in advance...

Answer №1

According to information from MDN (emphasis added):

[The HTMLFormElement: submit() method] is similar to activating a form's submit, but there are differences when invoking this method directly:

  • There is no submit event triggered, meaning the form's onsubmit event handler does not execute.
  • Constraint validation does not occur.

Instead, you can utilize the requestSubmit() method, which submits a form as if the submit button had been clicked (thus allowing the onsubmit handler to run).

Answer №2

When submitting a form programmatically with JavaScript, keep in mind that it won't trigger a submit event.

If you would like your code to display an alert but not submit the form, simply write the code to show the alert without submitting.

document.getElementById("submitBtn").addEventListener("click", function() {
    alert("Your custom message");
});

Alternatively, consider using a submit button to properly submit the form without relying on JavaScript.

Answer №3

Solution to your issue is to utilize an input of type submit:

<button id="submitButton" type="submit">

https://jsfiddle.net/johndoe/85rt7h62/9/

To make this work, you need to eliminate the click event listener that is submitting your form. Instead, listen for the form submit event and call preventDefault() to prevent the form from being submitted.

Answer №4

I stumbled upon this information and discovered the solution.

If you want to simulate an event using JavaScript, you can achieve it like this.

generate a submit event that bubbles up and cannot be cancelled

const form = document.getElementById('pform');

const evt = new Event("submit", {"bubbles":true, "cancelable":false});
// the event can be triggered from any element, not just the document
form.dispatchEvent(evt);

https://developer.mozilla.org/en-US/docs/Web/API/Event/Event

Answer №5

modify

<button id="myButton" type="button">Submit form</button>

into

<button id="myButton" type="submit">Submit form</button>

Answer №6

You have selected the button type ="button" option.

Consider switching to button type="submit".

By doing so, it will trigger an alert message.

Visit this jsfiddle link

Answer №7

method to programmatically invoke event

`const form = document.querySelector('#myform');

const customEvent = new Event('submit', {bubbles: true, cancelable: false});

form.dispatchEvent(customEvent);`

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

Exploring and cycling through numerous links using Selenium WebDriver in a node.js environment

Decided to switch from Casper.js to Selenium for access to more tools. Currently trying to loop through multiple links and navigate them using node.js along with selenium-webdriver. Struggling to find any helpful documentation or examples, as I keep enco ...

Having difficulty creating JSON data following retrieval of rows by alias in MySQL

I am encountering an issue while trying to fetch rows from two tables using a JOIN and aliases. The problem arises when I attempt to convert the fetched rows into JSON data and assign them to a JSON array. Below is the code snippet: $personal = $db->p ...

Transferring data from ng-init to <script> in AngularJS

Take a look at this code snippet: <div ng-init="companyData"> <script type="text/javascript"> window.timeline = new TL.Timeline('timeline-embed', sampleJson); </script> </div> Is there a method to include company ...

Issue with Electron dialog.showOpenDialog() Filters malfunctioning

Recently, I've been working on a modified version of an IDE on GitHub and encountered a major issue where the files were being saved to cookies instead of the computer. This prompted me to find a way to save and open files efficiently. While I managed ...

Ways to add a substantial quantity of HTML to the DOM without relying on AJAX or excessive strings

Currently, I am looking to update a div with a large amount of HTML content when a button on my webpage is clicked. The approach I am currently using involves the .html() method in JQuery, passing in this extensive string: '<div class="container-f ...

How can I use JavaScript fetch to retrieve data from a JSON file based on a specific value?

I am looking to extract specific values from a JSON array based on the ID of elements in HTML. How can I achieve this? [ { "product": "gill", "link": "x.com", "thumbnail": "gill.jpg ...

Issue encountered: ENOENT - There is no file or directory located at the specified path for ... .steampath

I am encountering an issue while attempting to launch the development server on a React project that has been dormant for quite some time. After executing npm install and npm start, I encountered the following error message. Despite my efforts to manua ...

Apologies, but Discord.js is unable to access the property "user" of a null object

I am facing a perplexing issue that I cannot seem to wrap my head around. The function works perfectly on one server but fails on another. Below is the snippet of code in question: const user = message.author; let servericon = message.guild.iconURL; let se ...

I'm looking for a way to connect to my X-UI database using node.js - can anyone

I am looking to develop an app in node.js that will allow me to create my own RESTful APIs using a x-ui Xray graphical management panel. My goal is to be able to handle operations such as creating, editing, and retrieving data through the HTTP protocol. In ...

.submit fails to function when the bound object has been updated via an ajax call

I managed to implement an AJAX commenting system where, upon clicking the Post Comment button, an ajax call is made instead of submitting the form traditionally. Everything was working smoothly until I tried refreshing the page with the comment submit butt ...

Passing slots to child components within a VueJS application - A helpful guide

Within my application, I frequently utilize a list and list_item component. To provide a general idea: contact_list.vue <template lang="pug"> .table .table-header.table-row .table-col Contact .table-col Info .tabl ...

Looking for an instance of a node.js ftp server?

I'm facing a challenge in creating a node.js application that can establish a connection with an FTP server to download files from a specific directory: Despite attempting to follow the instructions provided in the documentation for the ftp npm packa ...

Accessing Parent and Child Values in AngularJS Selections

I am seeking advice from experts on how to achieve the following desired results: Expected workflow chart: https://i.sstatic.net/9ZmmT.png Here is the default view: https://i.sstatic.net/H6xkZ.png Scenario 1: By clicking on the number "1", all items f ...

Res.render() is failing to display content

I'm facing an issue with my express route where it's not rendering a jade template properly. If I provide the wrong jade template string, I get the usual error indicating that the file couldn't be found to render in the browser. However, wh ...

Disable the button until all input fields contain text in ASP

Curious if anyone knows how to disable a button until all text boxes have input in ASP.NET and C#. Here is an image showing the scenario I'm referring to - wanting to gray out the commit button. Thanks, Chris! ...

Submitting a PDF document to the server with PHP Laravel through AJAX

Struggling to send a PDF file via AJAX to my server for handling by a PHP script in a Laravel project. The file doesn't seem to be making it to the server. Despite receiving a 200 response in the network, the server is returning 'file not presen ...

What is the best way to transfer an integer from my main application to a separate JavaScript file?

Currently, I am developing a complex code using React Bootstrap and focusing on creating a Dropdown list that fetches data from the backend database. <Dropdown> <Dropdown.Toggle variant="success" id="dropdown-basic"></D ...

Creating a Login Form with Node.js and MongoDB

Currently, I am working on a node.js application that is connected to a remote mongoDB server. Inside the database are specific custom codes that have been created and shared with selected users. The main objective is to restrict access to the rest of the ...

Why is the Google Map missing from the Bootstrap modal dialog?

I have multiple links on my website, each describing a different location with unique map data. I would like to display a modal bootstrap dialog with an embedded Google map when a user clicks on any of the links - ensuring that the location shown correspon ...

Create a roster of individuals who responded to a particular message

Can a roster be created of individuals who responded to a specific message in Discord? Message ID : '315274607072378891' Channel : '846414975156092979' Reaction : ✅ The following code will run: bot.on("ready", async () = ...