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...
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With