Store HTML datalist options in another file without using Javascript

1.2k Views Asked by At

In index.html there is a datalist in a <form> that looks like:

<input id="my_input" type="email" list="my_list" multiple>
<datalist id="my_list">
        <option value="Number 1">
        <option value="Number 2">
        <option value="Number ...">
        <option value="Number N-1">
        <option value="Number N">
</datalist>
<input type="submit"> <!-- Leaving out the form code for this MWE. -->

It is desirable for the (large number of) option items to be pulled out of the main HTML file and into some external file, without having to use Javascript to dynamically create the datalist.

Pseudo code demonstrating what is wanted:

# data.html
<datalist id="my_list">
        <option value="Number 1">
        <option value="Number 2">
        <option value="Number ...">
        <option value="Number N-1">
        <option value="Number N">
</datalist>

and

# index.html
<input id="my_input" type="email" source="data.html" list="my_list" multiple>
<input type="submit">

The solution doesn't have to be broken out exactly like above, as long as:

  1. The (large number of) option values are in a separate file.
  2. A form in index.html is able to get the selected datalist items to submit.
  3. Javascript isn't needed to construct the datalist in index.html.

The first thing I tried was HTML imports, but it turns out they're deprecated, so I didn't pursue it very far. Then I sunk a bunch of time into trying to do this with the object tag, but it seems Javascript is necessary to get the values.

Is there a way to do this in HTML?

1

There are 1 best solutions below

0
On

In any case you'll need a bit of Javacscript code to download and insert the HTML portion into the main HTML page.

But you can define a Custom Element that will extend the standard <input> element, by downloading with fetch() the file defined in the source attribute, and insert its content at the right place with insertAdjacentHTML( 'afterend', ... ):

//data-list.js
customElements.define( 'data-list', class extends HTMLInputElement {
    static get observedAttributes() { return [ 'source' ] }
    async attributeChangedCallback( name, old, file ) {
        let fs = await fetch( file )
        this.insertAdjacentHTML( 'afterend', await fs.text() )
    }
}, { extends: 'input' } )

The above Javascript can be defined inline or loaded with a <script> tag. The extended <input> element is defined by using the is='data-list' attribute:

<script src='data-list.js'></script>
...
<input is="data-list" id="my_input" type="email" source="data.html" list="my_list" multiple>
<input type="submit">