Search code examples
htmlweb-component

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>

Solution

  • You are doing it wrong. Though event bubbling from shadow DOM to owner document is somehow possible, it’s tricky and in general is a wrong approach. Instead of hiding button into shadow, one should use is= attribute of button:

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

    More info.