Accepted answer

You can pass the option text to your update function from your onchange function as:


So you'd end up with:

var select ='body')
  .on('change',function() { update(this.value, this.options[this.selectedIndex].text) }); // note: since you are setting value equal to the index, you can also use this.value instead of this.selectedIndex

function update(i, a) {

How this works: in your code you use d3 to append an HTML select element (Select object) with several HTML option elements (Option object) in it.

Then on the select element, the onchange function (which is a standard event of the select element) then passes the select element to its function handler, so in that function this represents the actual select element, and therefore this.value (Select value property) corresponds to the value of the select element (i.e. the value of the currently selected option in the select element).

The options property of the select element, i.e. this.options (Select options collection), gets you a list of all of the option elements within that select. Using the selectedIndex property of the select element, i.e. this.selectedIndex (Select selectedIndex property), you can grab the currently selected option element from the list as this.options[this.selectedIndex].

Since the this.options collection is a list of Option elements (Option object), to get the actual text of that option you can use .text on it. And that's how you end up with this.options[this.selectedIndex].text.

Related Query