Search code examples
observablehq

Get the label of an ObservableHQ radio button


Is there a way to obtain the label of a radio button?

For example I have

viewof classification = radio({
  options: [
    { label: "Underweight", value: "Underweight" },
    { label: "Healthy Weight", value: "Normal" },
    { label: "Overweight", value: "Overweight" },
    { label: "Obese", value: "Obese" }
  ],
  value: "Underweight"
})

If I wanted to access the "Healthy Weight" label instead of the classification value of "Normal", is it possible?


Solution

  • If you have control over the definition of the radio (i.e. this radio isn't being imported from a notebook you don't own), you could restructure this a bit to make that easier.

    e.g. in one cell:

    options = new Map([
      ["Underweight", "Underweight"],
      ["Normal", "Healthy Weight"],
      ["Overweight", "Overweight"],
      ["Obese", "Obese"]
    ]);
    

    and the radio cell:

    viewof classification = radio({
      options: [...options.entries()].map(([value, label]) => ({label, value})),
      value: "Underweight"
    })
    

    And in the cell you need to reference the label rather than the value:

    label = options.get(classification)