Home > other >  How to use select option value (string) inside a d3.Threshold.range() that needs an object in D3.js?
How to use select option value (string) inside a d3.Threshold.range() that needs an object in D3.js?

Time:05-21

Using d3.js I get the value of a select box and pass it to the .range() of a .scaleThreshold().

This is the select box:

<select id="color_scheme">
  <option value="d3.schemeOranges[7]">Orange</option>
<select>

This is how I get the value of the select box:

var color_scheme = d3.select("#color_scheme").property("value");

And this is the colorScale:

    const colorScale = d3.scaleThreshold()
        .domain([10, 100, 1000, 10000, 100000, 1000000])
        .range(color_scheme);

The problem is that in this case color_scheme is a string and it won't work inside the .range() brackets.

If you console.log it you just receive the string d3.schemeOranges[7] back.

But when you hardcode var color_scheme directly to color_scheme = d3.schemeOranges[7] it works.

And if you console.log it you receive the right object as expected:

[
    "#fff5eb",
    "#fee6ce",
    "#fdd0a2",
    "#fdae6b",
    "#fd8d3c",
    "#f16913",
    "#d94801",
    "#a63603",
    "#7f2704"
]

So the question is: how we can get the select value to work properly inside the .range()?

CodePudding user response:

I'd suggest the following. Change your input to:

<select id="color_scheme">
  <option value="schemeOranges">Orange</option>
<select>

Then in your js, using the string, the array is:

d3[color_scheme][7]
  • Related