1

I have a dropdown menu in my form. Each option has 3 data-attributes associated with it. When one option is selected I call a function that sets the values of hidden html objects to the value of each data attribute so I can pull that information on the next page. However, the value of the data-attributes keeps coming up as "undefined". What am I doing wrong?

 <script>
     function change_charge(x)
     {
     alert (x.dataset.amount); 
     }
 </script>

 <select name="description"  id="description" onchange="change_charge(this)">
     <option value="Test" data-amount="10.00" data-type="charge" >TEST      </option>
  </select>

I expect the alert to say the value of data-amount but instead it says "undefined"

I have also tried: alert (x.getAttribute('data-amount'));

But that returns "null".

Robin Thomas
  • 13
  • 1
  • 4

2 Answers2

5

x is the <select>, not the <option>. The select has no data- attributes.

If you want the option, use

var option = x.options[x.selectedIndex];
console.log(option.dataset.amount);
James
  • 20,957
  • 5
  • 26
  • 41
3

This answer shows how you can get a custom attribute from JavaScript.

Summary: you can use getAttribute()

x.getAttribute("data-amount");

EDIT:@James also makes a good point, which is x is the selector, not the option. Thus you will probably need a combination of our two answers:

x.options[x.selecetdIndex].getAttribute("data-amount");