Blending Web Components Into Standard HTML Forms
You can participate in the gathering up of a form's data prior to submission. It's a remarkably straightforward API to use.
By Jared White
Because until fairly recently this wasn’t a widely-supported and recognized feat, you’d be forgiven for thinking that you can’t yet add custom elements as controls in standard HTML forms.
Thankfully as of the latest major release cycle, all evergreen browsers support the FormDataEvent
which allows you to participate in the gathering up of a form’s data prior to submission.
Here’s a Pen with a working demonstration showing that a custom element can add one or more fields to its parent form. It’s a remarkably straightforward API to use.
form.addEventListener("formdata", event => {
event.formData.append(name, value)
})
Note that this isn’t the only spec which has been in the works for web component form controls. There’s also the ElementsInternals
API which provides for some additional capabilities to affect form behavior such as validation, label associations, and enhanced accessibility. There’s not yet full cross-browser support for this API, so for less complex requirements, we can leverage the FormDataEvent
for essential form participation today.