Nothing I do seems to be able to prevent the form from loading a new page. I have the following test code:
<form id="form" onsubmit="return false">
<input id='input'>
<input id='submit' type="button" value="click me">
</form>
<script>
var form = document.getElementById("form")
form.addEventListener("submit", (ev) => {
console.log("submit")
ev.preventDefault()
ev.returnValue = false
return false
})
form.dispatchEvent(new Event('submit'))
</script>
The page just loads and reloads over and over again. Is this a bug in firefox? I'm on version 60.7.0esr
dispatch event forces to submit the form unless you make it cancelable. You can also add <form onsubmit="return false">
a quick solution would be:
<form id="form" onsubmit="return false">
<input id='input'>
<input id='submit' type="button" value="click me">
</form>
<script>
var form = document.getElementById("form")
form.addEventListener("submit", (ev) => {
console.log("submit")
ev.preventDefault()
ev.returnValue = false
return false
})
let event = new Event("submit", {
bubbles: true,
cancelable: true,
});
form.dispatchEvent(event);
</script>
I hope this helps
You need to make the event cancelable
by adding a cancelable
property to the EventInit
Object that you need to pass to the Event
constructor. It is false
by default.
Consider MDN Event Documentation :
cancelable
: aBoolean
indicating whether the event can be cancelled. The default isfalse
.
var form = document.getElementById("form") form.addEventListener("submit", (ev) => { console.log("submit") ev.preventDefault() ev.returnValue = false return false }) form.dispatchEvent(new Event('submit', { cancelable: true }))
<form id="form" onsubmit="return false"> <input id='input'> <input id='submit' type="button" value="click me"> </form>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.