'One submit button is calling "onSubmit" for multiple unrelated forms on the same page?
I have a page with two forms. One main form and another which can be popped up in a modal, completely isolated from the main form in the DOM. They are not siblings or ancestors or anything. Both forms have an onSubmit
function and their own button with type=submit
. When I click the submit button in the modal form, it is also calling the onsubmit
function for the main form. I can't figure out how to prevent this from occurring.
The DOM looks (very roughly) like this:
<body>
<div id="app-root">
<...>
<form onsubmit="submitMainForm">
<button type="submit"></button>
</form>
</...>
</div>
<div id="modal-root">
<...>
<form onsubmit="submitModal">
<button type="submit"></button>
</form>
</...>
</div>
</body>
The forms are not overlapping* (in the DOM, see below re. React) and the buttons are in their respective forms.
Both submit functions are in the general form:
e => {
e.preventDefault();
doRelevantSubmitActions();
}
Based on some other similar SO questions, I've also tried giving the buttons different name
values or returning false from the onSubmit
functions but nothing seems to prevent the one button from calling both functions.
I'd prefer to maintain the type=submit
pattern as opposed to just using onclick
functions as it comes with other QOL functionality (like submitting a form via the enter key)
*My only sliver of an idea is it could be a React issue? The modal form IS a child of the main form in the React tree, but it uses a Portal to the modal-root
div to keep them separated in the actual DOM. I don't think the React component is related to this problem but I felt it was an important disclosure.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|