home ~ projects ~ socials

Do Something With A Form Before Submitting It

Introduction

I'm working on a personal browser extension that stores some values in localStorage while you're working with it1. I want the data to clear when you hit the submit button. This is how I'm doing it.

HTML

<form id="example-form">
  <input 
    type="text" 
    name="example-input" 
    value="alfa" 
    />
  <input type="submit" value="submit" />
</form>

<div id="example-output">waiting...</div>

Output

waiting...

JavaScript

const formEl = document.querySelector(
  '#example-form'
);

formEl.addEventListener(
  'submit', 
  (event) => {
    event.preventDefault();
    doSomething()
    setTimeout(() => {
      formEl.submit();
    }, 2000)
  }
)

function doSomething() {
  const outputEl = document.querySelector(
    '#example-output'
  );
  outputEl.innerHTML = "submitted";
}
-- end of line --

References

Footnotes

The extension uses popover and I save the data so that if I accidentally hit Escape I don't lose what I was working on.