JS Form Two Submit Options

I have a form using has a ID and JS file listening to the submit method. I've got another JS code to change the ID field once the page is loaded. I'm then wanting to post that somewhere different. The issue is on page load the event listener is set on the first ID and even if I change it, that method is being called. How can I reset this? var form = document.getElementById('my-form'); form.addEventListener('submit', function(event) { console.log('always called even if ID is changed after page load') })
3 Replies
Joao
Joao9mo ago
The point of using ids is to have unique labels for elements. Changing this is possible but most definitely not the best way to go about it as it's just counter-intuitive. Can you better describe what you are trying to do? Also, please share a link to codepen or similar to have a better idea of what you've tried so far.
NZAA
NZAAOP9mo ago
Yeah, it's a registration / payment form. Default is via one method, but if a user opts for another it's going to go down a different path. I don't want to duplicate the form and there's obviously data in the form which needs to be posted on both options.
Joao
Joao9mo ago
To me those look like separate actions. If you need to allow payments from guests (non registered accounts), but still collect some information about them, you can have a few inputs asking for whatever details you need. If the user is already registered and logged in, however, then simply prefill those details for them. But anyway, I'll leave it up to you how you want to proceed on this. To remove an event listener, use removeEventListener much like you do to add one, except that you need to provide a reference to the function you're running so you can't provide it as an anonymous function.
function callback() { /* ... */ }

element.addEventListener('click', callback);
element.removeEventListener('click', callback);
function callback() { /* ... */ }

element.addEventListener('click', callback);
element.removeEventListener('click', callback);
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener This way, you can still re-use the same ID on the form and simply add a new listener for another function.
Want results from more Discord servers?
Add your server