Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a slotted input field's form attribute to a form inside shadow dom?

I have a custom element like this:

<my-magic-form>
    #shadowRoot:
    <form id="some_id_name_invisible_to_end_users">
      <input disabled name="entry_id"></input>
      <slot name="fields_toFill"></slot>
    </form>
</my-magic-form>

The users of my widget are supposed to add their own input fields like this:

<my-magic-form>
  <input slot="fields_toFill" value="some_value1"/>
  <textarea slot="fields_toFill"/>
</my-magic-form>

My question is: how can I link those two slotted <input> and <textarea> controls to the <form> element inside the shadow DOM of my widget? The end users are not required to know the inner form's id of my widget, so they cannot set the form attribute when they author; and I've tried programmatically setting this attribute only to find out that this attribute is read-only!

like image 984
Jinghui Niu Avatar asked Sep 19 '25 21:09

Jinghui Niu


1 Answers

A simple solution is to move the light DOM into the Shadow DOM content. Listen to the slotchange event then move the assignedNodes() before the <slot> element.

var form = this.shadowRoot.querySelector( 'form' )
var slot = this.shadowRoot.querySelector( 'slot' )

slot.addEventListener( 'slotchange', () => {
    for (var field of slot.assignedNodes()) {
        form.insertBefore( field, slot ) 
    } 
} )

Alternately, if you don't want to move the light DOM fields, you should duplicate them as <input type="hidden"> fields, for exemple whan the <form> is submitted.

like image 176
Supersharp Avatar answered Sep 21 '25 10:09

Supersharp