This is my HTML (problem is described below):
//Form 1 is called through a modal that is disconnected from form 2:
<div class="modal">
<form action="/user" method="POST" id="form-1">
<input type="text" id="username" name="username">
<button>Submit</button>
</form>
</div>
//Form 2 is appended in #form-1 listener
<div id="user-info" class="user-details">
<p>Username: <%= user.username %></p>
<% if(user.email) { %>
<p>Email: <%= user.email %></p>
<% } else { %>
<form action="/user?_method=PATCH" method="POST" id="form-2">
<input type="email" id="user-email" name="user-email">
<button>Submit</button>
</form>
<% } %>
</div>
The two ajax listeners/calls:
$('#form-1').submit(function(e) {
e.preventDefault();
const user = $(this).serialize();
$.post('/user', user, function(data) {
$('#user-info').append(
`<p>Username: ${data.username}</p>
<form action="/user?_method=PATCH" method="POST" id="form-2">
<input type="email" id="user-email" name="user-email">
<button>Submit</button>
</form>`
)
});
});
$('#form-2').submit(function(e) {
e.preventDefault();
const user = $(this).serialize();
$.ajax({
url: '/user',
data: user,
type: 'PATCH',
success: function(data) {
$('#user-info').append(
`<p>Username: ${data.username}</p>
<p>Email: ${data.email}</p>`
)
}
});
});
The first one (#form-1) runs without a problem.
However, the second one (#form-2) is never run even though it is the only one that is called.
It only works when I comment out the first one (in other words, when I place it in the beginning of the script file. I think the second one is being ignored.
Is there a way to listen to both forms simultaneously?