0

I have a select menu that is a stimulus target. Each option of that select has a custom data attribute. When that select changes I need the stimulus controller to read a dataset attribute from the selected option...not the select menu target.

In the controller action, event.currentTarget is the select menu where the target attribute is set. Rather, I expecting it to be the selected option.

// this correctly returns the selected options value attribute.  Stimulus must know what you want in this case.
event.currentTarget.value



// However, calling this returns the classList for the target...which is the select, not the option.
event.currentTarget.classList



// And, calling this returns 'undefined' because data-value is not defined on the target select, it's defined on the selected option...which is not the currentTarget.
event.currentTarget.dataset.value

So, when I call event.currentTarget.dataset.value in the stimulus controller I'm actually looking for data-value='xxx' from the selected option. But, instead stimulus is looking for data-value on the target select menu.

How would I return the 'xxx' data-value attribute from the selected option when the target menu is changed?

hellion
  • 4,602
  • 6
  • 38
  • 77
  • 1
    See [this answer](https://stackoverflow.com/a/1085810/2622934). You should be able to use something like `event.currentTarget.options[event.currentTarget.selectedIndex]`. Then read the data attributes there. – cschroed Apr 02 '21 at 17:34
  • Thanks @cschroed. That worked perfectly. I knew it'd be easy. If you wanna move that comment to an answer I'll mark it the one. – hellion Apr 02 '21 at 17:48
  • 1
    No problem. Since this wasn't really directly related to an issue with Stimulus, I'm going to suggest that we close this question as a dup of the other more general one about getting at ` – cschroed Apr 02 '21 at 17:51

0 Answers0