Vanilla JS alternative to @submit.prevent="myMethod"

Duncan McClean :

I use Vue.js for most of my JavaScript related stuff. However, I've come across a situation where I want to replicate some functionality that Vue achieves but in Vanilla JS.

Vue gives you this modifier you can put on a form element.

@submit.prevent="myMethod"

I want to do the same thing. I want the user to click a button, some JS code to happen and then for the form to be submitted.

This is one thing that I've already tried but the form submitted before the JS actually got executed.

var form = document.getElementById('a-form');

form.addEventListener('submit', event => {
// my code
});

Thanks in advance for your help!

Boussadjra Brahim :

it's preventDefault function :

var form = document.getElementById('a-form');

form.addEventListener('submit', event => {
 event.preventDefault();

//code
});

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29808&siteId=1