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?
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.
Use the .property()
method:
d3.select("#objectID").property("value")
You don't need to use D3 to do that:
var sel = document.getElementById('myselect');
console.log(sel.options[sel.selectedIndex].value)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With