Brian J Brian J - 4 months ago 8
jQuery Question

How to create only one li element per call to d3.append?

I'm passing in the name of a checkbox option in JQuery d3 in order to render a new tab

li
element with the same name.

But what I tried passing in the option name eg, "option1" creates a new tab for each letter in the string using the
.data(val)
option.

So in my example below
val = "option1"
and I create the tab like this:

d3.select("ul#chartTabs")
.selectAll("li")
.data(val)
.enter()
.append('li')
.insert("a", ":first-child")
.attr("data-toggle", "tab")
.attr("id", function(val, i){ var result = val + i; return result; })
.text(function(d){ return d; })


Question:

How can I create only one tab per call to d3.append?

This is the current output when passing in the val
"option1"
. Which is not as expected as it creates a new tab for each letter. Instead of a single button with value option1.

enter image description here

Answer

d3 is coercing your string to an array, you could just use .data([val]), or skip the data-binding all together since you aren't really using it:

d3.select("ul#chartTabs")
  .append('li')
  .insert("a", ":first-child")
  .attr("data-toggle", "tab")
  .attr("id", val + "0")
  .text(val);

If you really want multiple li, don't call this code iterative-ly, you then want the data-binding.

d3.select("ul#chartTabs")
  .selectAll("li")
  .data(["option1", "option2", "option3"])
  ...