0

I would like to build the following radio buttons procedurally.

<input type="radio" name="bees">5<br />
<input type="radio" name="bees">10<br />
<input type="radio" name="bees">20

If I use code such as the following:

function build_colony() {
    const bees_list = [5, 10, 20];
    d3.select('.colony)
      .selectAll('input')
      .data(bees_list)
      .enter()
      .append('input')
      .attr('type', 'radio')
      .attr('name', 'bees')
      .text(d => d);
}

I get a closing </input>:

<div class="colony">
    <input type="radio" name="bees">5</input>
    <input type="radio" name="bees">10</input>
    <input type="radio" name="bees">20</input>
</div>

How do I mismatch D3's closing tag?

Vrokipal
  • 784
  • 5
  • 18

1 Answers1

3

You don't want your text nested within your input. So, I'd use a placeholder span to handle my data-binding so that your input and label can be siblings.

<!DOCTYPE html>
<html>

<head>
  <script src="https://d3js.org/d3.v5.min.js"></script>
</head>

<body>
  <div class="colony"></div>
  <script>
    let bees_list = [5, 10, 20];
    
    var s = d3.select('.colony')
        .selectAll('span')
        .data(bees_list)
        .enter()
        .append('span');

      s.append('input')
        .attr('type', 'radio')
        .attr('name', 'bees')
        .attr('id', d => d);
        
      s.append('label')
        .text(d => d)
        .attr('for', d => d);
  </script>
</body>

</html>
Mark
  • 106,305
  • 20
  • 172
  • 230
  • Your approach is cleaner, for sure, but it also sometime introduces undesirable line breaks that are tricky to dodge. – Vrokipal Jun 07 '19 at 14:05
  • @Vrokipal, can you elaborate on what you mean by *undesirable line breaks*? My runnable snippet above has no line breaks. – Mark Jun 07 '19 at 14:22
  • 1
    Add the style `.colony { width: 200px; }` and replace the first assignment with `let bees_list = d3.range(30).map(d => 2**d);`. Then some of the inputs will be separated from their labels. – Vrokipal Jun 07 '19 at 14:30
  • Ironically, the flexibility of these alternative styles is facilitated by your more correct solution. It's somewhat of an orthogonal issue, for which one can find a multitude of mediocre solutions, e.g. https://stackoverflow.com/q/14608156/9295807 , https://stackoverflow.com/a/512769/9295807 – Vrokipal Jun 07 '19 at 14:34