0

I want to get the text of a selected option from a select element. I know I can make this work by using this:

let e = document.getElementById(id)
return e.options[e.selectedIndex].text

But I have select-elements without an id but with a data-attribute, e.g. : (they are just placeholders)

<select data-statement="1">
           <option>SELECT</option>
           <option>UPDATE</option>
           <option>INSERT</option>
</select>

How can I get the selected option text (e.g. into the console.log()) by using the data-attribute? I tried

var countStatement = document.querySelectorAll('[data-statement]');
console.log(countStatment);

That doesnt work.

Can you tell me what I am doing wrong? :)

Background information for maybe better understanding: I create some select elements by clicking on a button. After that they get filled with different data. In the end I want to display the selected options in an input element. I can do this by giving every single element an Id but thats quite a work-around in my opinion :D

If you have better ways to implement my wanted features, let me know ;) (maybe data-attributes are not meant to be used for this kind of problem)

PS: I am new to programming so be kind if I have not read every documentation of javascript :D

tacoshy
  • 10,642
  • 5
  • 17
  • 34

0 Answers0