Get data attribute onchange event

Viewed 4736

I'm trying to retrieve a custom data attribute that I did add to the option element, but it's not working.

<p>Select a new car from the list.</p>

<select id="mySelect" onchange="myFunction(this.data-price)">
  <option data-price="250" value="Audi">Audi</option>
  <option data-price="130" value="BMW">BMW</option>
  <option data-price="120" value="Mercedes">Mercedes</option>
  <option data-price="400" value="Volvo">Volvo</option>
</select>

<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
<p id="demo"></p>
function myFunction(val) {
  document.getElementById("demo").innerHTML = "You selected: " + val;
  console.log(val);
}

The thing is when I switch the function call to:

onchange="myFunction(this.value)">

It returns the value correctly, but when I select the data-price, it returns undefined to the console.

2 Answers

Your code is saying "get data property" and subtract a variable "price" from it. Second issue, you are selecting the property on the select when it lives on the option. You can not act use it like value.

You should be using dataset on the selected option

function myFunction(sel) {
  var opt = sel.options[sel.selectedIndex];
  var price = opt.dataset.price
  document.getElementById("demo").innerHTML = "You selected: " + price;
}
<p>Select a new car from the list.</p>

<select id="mySelect" onchange="myFunction(this)">
  <option data-price="250" value="Audi">Audi</option>
  <option data-price="130" value="BMW">BMW</option>
  <option data-price="120" value="Mercedes">Mercedes</option>
  <option data-price="400" value="Volvo">Volvo</option>
</select>

<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
<p id="demo"></p>

Simply access the data attribute of the selected option (jQuery example since you tagged it):

$("#mySelect").change(function() {
  const $this = $(this); // Cache $(this)
  const dataVal = $this.find(':selected').data('price'); // Get data value
  const selectedVal = $this[0].value;
  alert(`${dataVal}, ${selectedVal}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Select a new car from the list.</p>

<select id="mySelect">
  <option data-price="250" value="Audi">Audi</option>
  <option data-price="130" value="BMW">BMW</option>
  <option data-price="120" value="Mercedes">Mercedes</option>
  <option data-price="400" value="Volvo">Volvo</option>
</select>

<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
<p id="demo"></p>

Related