Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submitting a form using a custom button using HTML Web Components

I have defined a custom DOM element, but when placed inside a form, it does not submit it. How can I get the form to submit when I click the button?

<form action="/foo" method="GET">
  <my-button type="submit">click me</my-button>
</form>

This is the prototype configuration for the custom element:

myButton = Object.create(HTMLButtonElement.prototype);

The template for the button looks like this:

<template>
  <button type="submit" id="button"><content></content></button>
</template>
like image 990
Ben Aston Avatar asked Feb 24 '26 23:02

Ben Aston


1 Answers

Came across this question today, but found a more modern alternative subsequently: web components can now be native form elements. There's a great read on the topic here.

The long and the short of it is you can now associate custom components with a form, meaning they're included in the form's elements property - a HTMLFormControlsCollection of all the elements controlled by the form.

To do this, you need to add the following to your component:

class MyComponent extends HTMLElement {
  static get formAssociated() { return true; }

  constructor() {
    super();
    this.internals = this.attachInternals();
  }
}

this.internals will then contain everything you need to interact with the form in question, e.g. this.internals.form, this.internals.setFormValue(), this.internals.checkValidity().

For the submit button, you could, for example, use:

connectedCallback() {
  const { internals: { form } } = this;

  this.buttonEl.addEventListener('click', () => form.submit());
}
like image 125
SRack Avatar answered Feb 26 '26 13:02

SRack