Re: [WICG/webcomponents] Form-associated custom elements: being a submit button (#814)

So I've been playing with this in my project at work and this seems like it mimics what I'd like to see on this front:

```javascript
HTMLFormElement.prototype.requestSubmit = function() {
  if (this.requestValidity() === false) {
    return;
  }
  const submitEvent = new Event('submit', { cancelable: true });
  this.dispatchEvent(submitEvent);
  if (!submitEvent.defaultPrevented) {
    this.submit();
  }
}
```

While this could live on `ElementInternals`, it doesn't quite make sense to make it `ElementInternals.prototype.submitForm` because `form` is already exposed by `ElementInternals` and other APIs might wish to make use of this API as well (other than submit buttons) like watching for an Enter keydown event:

```javascript
class SomeCustomElement extends HTMLElement {
  #internals = this.attachInternals();

  /** Interesting custom element things */

  connectedCallback() {
    this.someTarget.addEventListener('keypress', event => {
      if (this.#internals.form && event.code === 'Enter') {
        this.#internals.form.requestSubmit();
      }
    }
  }
}
```

Since `ElementInternals.prototype.setFormValue` will accept a `FormData` object, this could also enable logical submissions from within nested forms:

```html
<form id="rootForm">
  <x-personal-info-form></x-personal-info-form>
  <x-address-form></x-address-form>
  <x-ds-button-row></x-ds-button-row>
<form>
```

Where any `Enter` keypress from `x-personal-info-form` or `x-address-form` could submit the form. The `x-ds-button-row` element could include styled reset and submit buttons. Both of which will work for all the forms.

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/WICG/webcomponents/issues/814#issuecomment-840841615

Received on Thursday, 13 May 2021 21:20:31 UTC