Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript e.preventDefault(); not working on submit()

Tags:

javascript

i have a problem when submitting form with 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");

});

it supossed to be showing alert() and cancel submitting.

what's wrong with my code?

thanks in advance...

like image 404
Ching Ching Avatar asked Dec 15 '22 05:12

Ching Ching


1 Answers

Submitting a form programmatically, using JavaScript, does not trigger a submit event.

If you want your code to show an alert and not submit the form, then write it so it just shows an alert.

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

Alternatively, use a submit button to submit the form (instead of JavaScript).

like image 80
Quentin Avatar answered Dec 31 '22 01:12

Quentin