25

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
  • 62,943
  • 126
  • 334
  • 542

4 Answers4

53

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
  • 143,130
  • 81
  • 406
  • 459
Moop
  • 3,414
  • 2
  • 23
  • 37
33

Use the .property() method:

d3.select("#objectID").property("value")
Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Anish Agarwal
  • 1,793
  • 19
  • 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
  • 143,130
  • 81
  • 406
  • 459
Stephen Thomas
  • 13,843
  • 2
  • 32
  • 53
0

I've also seen

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

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

Azrantha
  • 419
  • 5
  • 10
  • 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