formData in web-components
Hello, I made a web component:
This is the html:
And it works, the form element recognizes
Why?
class Toggle extends HTMLElement {
#toggle = /*html*/`
<input type="checkbox" ${this.checked ? 'checked' : ''} />
`
constructor() {
super()
const shadow = this.attachShadow({mode: 'open'})
shadow.innerHTML = this.#toggle
this.internals = this.attachInternals()
shadow.querySelector('input').addEventListener('input', ({currentTarget}) => {
this.checked = currentTarget.checked
})
}
static formAssociated = true;
get checked() {
return this.hasAttribute('checked');
}
set checked(isChecked) {
this.internals.setFormValue(this.getAttribute('value'))
isChecked ? this.setAttribute('checked', '') : this.removeAttribute('checked')
}
}
customElements.define('my-toggle', GfToggle)class Toggle extends HTMLElement {
#toggle = /*html*/`
<input type="checkbox" ${this.checked ? 'checked' : ''} />
`
constructor() {
super()
const shadow = this.attachShadow({mode: 'open'})
shadow.innerHTML = this.#toggle
this.internals = this.attachInternals()
shadow.querySelector('input').addEventListener('input', ({currentTarget}) => {
this.checked = currentTarget.checked
})
}
static formAssociated = true;
get checked() {
return this.hasAttribute('checked');
}
set checked(isChecked) {
this.internals.setFormValue(this.getAttribute('value'))
isChecked ? this.setAttribute('checked', '') : this.removeAttribute('checked')
}
}
customElements.define('my-toggle', GfToggle)This is the html:
<form>
<my-toggle name="bla" value="foo"></my-toggle>
</form><form>
<my-toggle name="bla" value="foo"></my-toggle>
</form>And it works, the form element recognizes
my-togglemy-toggle as a member of the form. But console.log(new FormData(form))console.log(new FormData(form)) gives me an empty FormData object.Why?
