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/
d3. select selects the first matching element whilst d3. selectAll selects all matching elements. Both functions take a string as its only argument.
attr() function is used to set the attribute of the element that is selected. The name of the attribute and value of the attributes are to be set using this function.
selectAll() function in D3. js is used to select all the element that matches the specified selector string. Parameters: This function accepts single parameter HTML tag as a parameter. Return Value: This function returns the selected elements.
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.
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