Govind Samrow Govind Samrow - 4 months ago 25
Javascript Question

how to get select option data attribute value in JavaScript

I want to get data attribute value from selected option.

<option value="21" data-rc="25" data-clnc="10">Treatment</option>

var rc = ?
var clnc = ?


No jQuery please only JavaScript :)

Answer

You can read them out via dataset property.

var option = document.getElementsByTagName("option")[0];

console.log(option.dataset.rc)
console.log(option.dataset.clnc)
<option value="21" data-rc="25" data-clnc="10">Treatment</option>

Or, if you want to get the values of the selected option:

var selection = document.getElementById("mySelect");

selection.onchange = function(event){
  var rc = event.target.options[event.target.selectedIndex].dataset.rc;
  var clnc = event.target.options[event.target.selectedIndex].dataset.clnc;
  console.log("rc: " + rc);
  console.log("clnc: " + clnc);
};
<select name="selection" id="mySelect">
<option value="21" data-rc="25" data-clnc="10">Treatment</option>
<option value="21" data-rc="23" data-clnc="30">Treatment1</option>
<option value="21" data-rc="31" data-clnc="50">Treatment2</option>
<option value="21" data-rc="14" data-clnc="75">Treatment3</option>
</select>