Reputation: 65610
How can I set the value of a <select>
element, using D3.js?
I'm trying this:
d3.select('#myselect').attr('value', 'France');
But it isn't working.
JSFiddle here: http://jsfiddle.net/06z9tnzs/
Upvotes: 12
Views: 8361
Reputation: 381
Another way to set value by d3.js
d3.select('#myselect').node().value = 'France';
Upvotes: 1
Reputation: 8616
You need to use property instead of attr for setting the value.
d3.select('#myselect').property('value', 'France');
From the d3 docs:
Some HTML elements have special properties that are not addressable using standard attributes or styles. For example, form text fields have a value string property, and checkboxes have a checked boolean property. You can use the property operator to get or set these properties, or any other addressable field on the underlying element, such as className.
https://github.com/mbostock/d3/wiki/Selections#property
Albert's comments are also correct regarding your JSFiddle missing the d3.js reference and not specifying the id of "myselect" on the select element.
Upvotes: 20
Reputation: 141
I may be wrong, but is it because you did not include d3.js?
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
I can't see it in the frame source for some reason. Also, select should have a id of myselect
<select>
<option value="England">England</option>
<option id = "myselect" value="France">France</option>
<option value="Italy">Italy</option>
</select>
Upvotes: 1