23

I want to get the value of the selected option from a dropdown list, in D3.js.

<select>
<option data-graph="1">1</option>
<option value="2">2</option>
</select>

I have seen this question which explains how to get the value when the select changes:

d3.select("#myselect").on("change", change)
function change() {
    this.options[this.selectedIndex].value
}

But how can I get the selected value on page load, not when the select is changed?

Community
  • 1
  • 1
Richard
  • 57,831
  • 112
  • 317
  • 501

4 Answers4

51

I found this to be the simplest:

d3.select("#objectID").node().value; 

Which is the text of the selected option in the following node: <select id="objectID"></select>

Note that d3.node() is documented at https://github.com/mbostock/d3/wiki/Selections#node and the .value property of an HTMLInputElement is documented on MDN at https://developer.mozilla.org/en/docs/Web/API/HTMLInputElement.

Mark Amery
  • 127,031
  • 74
  • 384
  • 431
Moop
  • 3,257
  • 1
  • 23
  • 35
33

Use the .property() method:

d3.select("#objectID").property("value")
Mark Amery
  • 127,031
  • 74
  • 384
  • 431
Anish Agarwal
  • 1,715
  • 18
  • 19
14

You don't need to use D3 to do that:

var sel = document.getElementById('myselect');
console.log(sel.options[sel.selectedIndex].value)
Mark Amery
  • 127,031
  • 74
  • 384
  • 431
Stephen Thomas
  • 13,315
  • 2
  • 28
  • 49
0

I've also seen

d3.select("#objectID")[0][0].value

But I'm quite sure this is generally a bad idea...

Azrantha
  • 399
  • 5
  • 9
  • https://github.com/mbostock/d3/wiki/Selections - "However, you can still loop over elements manually if you wish: there's an each operator which invokes an arbitrary function, and selections are arrays, so elements can be accessed directly (e.g., selection[0][0])" - It seems this access method is mainly intended for looping, and, in my not-very-experienced opinion, is slightly less clear than the other answers. – Azrantha Jan 12 '16 at 12:30