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.


<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>
<p id="result"></p>


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