I have some HTML forms on the same page that are toggled sequentially one after another, after the previous one has been submitted. The user is able to navigate back and forth between them, so I need to remove submit event listeners after they have been triggered, so I can reattach them again if needed.
I am currently attaching submit event handlers inside the "rendering process" for each one of them, removing the event handler after executing the function like this:
form.addEventListener('submit', submitStepOne)
function submitStepOne(e) {
e.preventDefault()
sendData()
form.removeEventListener('submit', submitStepOne)
}
same code for multiple form elements (submitStepTwo
, submitStepThree
…)
Because I don't want to keep repeating the same code, I want to create a global "submit step and go to next one" function, which I thought could look something like this:
const submitStep = (event, stepNo, trigger) => {
event.preventDefault()
toggleStep(stepNo)
trigger.removeEventListener('submit', submitStep)
}
I thought I could attach the event handler to the submit button like this, using .bind()
(tip from https://stackoverflow.com/a/23024673/10727821):
PAGES.step3.functions = function() {
console.log('step 3')
let trigger = this.domElement.querySelector('form')
trigger.addEventListener('submit', submitStep.bind(null, event, 4, trigger))
}
PAGES
is an object containing the DOM element for each of the steps as well as corresponding functions for each page. PAGES.stepX.functions()
is called each time a step is toggled with toggleStep(step)
.
However, I'm getting an Uncaught TypeError: Cannot read property 'preventDefault' of undefined
. How could I rewrite the function so I can properly pass parameters to it?
Thankful for any hints!