I would like to fill an html drop-down list from values in an array.
Poor me I have just managed to write
viewof value = html`<input type=select>`
Any hints is welcome
I would like to fill an html drop-down list from values in an array.
Poor me I have just managed to write
viewof value = html`<input type=select>`
Any hints is welcome
Now going further into the tutorial material I discovered how to create such a static drop-down list
html`<select> <option>one</option> <option>two</option> <option>three</option> </select>`
The question remains for having the items in the menu coming from an array…
Say you have an array of color names:
colors = ["red", "green", "blue"]
You can use the DOM.select convenience method to create a drop-down menu to choose one of them:
viewof color = DOM.select(colors)
For more control over how the menu is rendered, use array.map within the html
tagged template literal:
viewof color = html`<select>${colors.map(color => `
<option value=${color}>${color}</option>`).join("")}
</select>`
I really like the template literals and how easy it is to use values from other cells / javascript.
Here I set attributes and labels are different from values:
viewof selected_option = html`<select>${Object.keys(pre_defined_options).map((d) =>
"<option value='" + d + "' " + (d === 'brocade' ? 'selected' : '') + " >"
+ pre_defined_options[d].label
+ "</option>")}
</select>`
and pre_defined_options looks like
{ snow: { label: 'White stuff', other_attribute: 5 },
brocade: { label: 'Japanese Brocade', other_attribute: 7 }
}
I’ve done something similar in
https://beta.observablehq.com/@jjimenez/altered-world-altered-even-further