JavaScriptNo Comments

default thumbnail

Here is how to retrieve a custom data attribute value onchange event in javascript. Use the below code step by step to get the data attribute value.

HTML

<select id="mySelect" onchange="myFunction(this)">
  <option data-price="50" value="Audi">Audi</option>
  <option data-price="100" value="BMW">BMW</option>
  <option data-price="150" value="Mercedes">Mercedes</option>
  <option data-price="200" value="Volvo">Volvo</option>
</select>
<p id="result"></p>

Javascript

function myFunction(a) {
  var opt = a.options[a.selectedIndex];
  var price = opt.dataset.price
  document.getElementById("result").innerHTML = "You selected: " + price;
}

Select the car from select options. The price of car will be there.

Be the first to post a comment.

Add a comment