Govind Samrow Govind Samrow - 1 year ago 107
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 Source

You can read them out via dataset property.

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

<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 =[].dataset.rc;
  var clnc =[].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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download