Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the value of a <select> element in D3?

Tags:

d3.js

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/

like image 673
Richard Avatar asked Mar 09 '15 00:03

Richard


People also ask

What do the select () and selectAll () functions in d3 do?

d3. select selects the first matching element whilst d3. selectAll selects all matching elements. Both functions take a string as its only argument.

What is attr in d3?

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.

What does d3 selectAll return?

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.


1 Answers

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.

like image 174
David Anderson Avatar answered Oct 14 '22 05:10

David Anderson