Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3.js: get value of selected option?

Tags:

d3.js

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?

like image 547
Richard Avatar asked Sep 18 '13 22:09

Richard


3 Answers

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.

like image 198
Moop Avatar answered Nov 11 '22 06:11

Moop


Use the .property() method:

d3.select("#objectID").property("value")
like image 33
Anish Agarwal Avatar answered Nov 11 '22 07:11

Anish Agarwal


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

var sel = document.getElementById('myselect');
console.log(sel.options[sel.selectedIndex].value)
like image 14
Stephen Thomas Avatar answered Nov 11 '22 06:11

Stephen Thomas