I need to connect a script for processing submission inside a form
tag.
There was a need that after pressing the submit button on the form there would be no redirection, but it is necessary that this script works ONLY FOR THIS FORM.
I tried to insert a script inside a form
tag and a button
tag, but the browser stripped this script insertion from the tags after opening the page.
Is there a way to attach a script locally to a form
so that it is only called for that form?
<div class="template_printer">\n
<form action="subscribe.php" method="POST">
<div>
<label for="name">Name</label>
<input type="text" name="name" id="name" />
</div>
<div>
<label for="email">Email</label>
<input type="email" name="email" id="email" required/>
</div>
<p role="alert" class="status-failure" hidden>Connection failure, please try again.</p>
<p role="alert" class="status-busy" hidden>Busy sending data, please wait.</p>
<button type="submit">Submit</button>
</form>
</div>
document.addEventListener('submit', e => {
const form = e.target;
const statusBusy = form.querySelector('.status-busy');
const statusFailure = form.querySelector('.status-failure');
fetch(form.action, {
method: form.method,
body: new FormData(form)
})
.then(res => res.text())
.then(text => new DOMParser().parseFromString(text, 'text/html'))
.then(doc => {
const result = document.createElement('div');
result.innerHTML = doc.body.innerHTML;
result.tabIndex = -1;
form.parentNode.replaceChild(result, form);
result.focus();
})
.catch(err => {
Array.from(form.elements).forEach(field => field.disabled = false);
lastActive.focus();
statusBusy.hidden = false;
statusFailure.hidden = false;
});
const lastActive = document.activeElement;
statusBusy.hidden = false;
statusBusy.tabIndex = -1;
statusBusy.focus();
Array.from(form.elements).forEach(field => field.disabled = true);
statusFailure.hidden = true;
e.preventDefault();
});