observablehq / stdlib

The Observable standard library.
https://observablehq.com/@observablehq/standard-library
ISC License
967 stars 83 forks source link

Feature Request: Set default select value #61

Closed motleydev closed 6 years ago

motleydev commented 6 years ago

Pass an option parameter to select to indicate which value should be default. Would look something like:

DOM.select(arr, defaultValue)

Something like this should work:

export default function(values, selected) {
  var select = document.createElement("select");
  Array.prototype.forEach.call(values, function(value) {
    var option = document.createElement("option");
    option.value = option.textContent = value;
    if (option.value === selected) option.selected = true; <--------
    select.appendChild(option);
  });
  return select;
}
mbostock commented 6 years ago

(Duplicate #57.) We’re probably going to deprecate DOM.select and related methods (see #31) in the near future in favor of HTML tagged template literals, so I don’t think it makes sense to add new functionality at this time.

For a static dropdown, I’d say:

html`<select>
  <option value="red">red</option>
  <option value="green" selected>green</option>
  <option value="blue">blue</option>
</select>`

For a data-driven one, something like:

colors = ["red", "green", "blue"]
html`<select>${colors.map(c => `
  <option value="${c}" ${c === "green" ? " selected" : ""}>${c}</option>`)}
</select>`