0

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();
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Nord
  • 11
  • 2
  • Target the form for the submit event listener, not the entire document. Eg. `document.querySelector('.template_printer form').addEventListener('submit', ...` – Rory McCrossan Jul 08 '22 at 09:46
  • Also, note that you don't need to add a comment for *every* line of code. Ironically, that usually makes the code harder to read and understand. – Rory McCrossan Jul 08 '22 at 09:50

0 Answers0