cronox
cronox

Reputation: 33

How to get data attribute values from html select?

I want to create a form where if I choose a name from a selection. The next input field will be autofilled.

It works with the value of the selected item, but I can't get it work with data tags.

Here is some simplified HTML:

<select class="select"  id="test " name="" onchange="myFunction(event)">
    <option disabled selected>Choose Database Type</option>
    <option data-adr="xyz" value="id1">Test name1</option>
    <option data-adr="fsd" value="id2">Test name2</option>
    <option data-adr="sss" value="id3">Test name3</option>
</select>

<input class="form-control" id="myText" type="text" value="-">

JavaScript (this works):

function myFunction(e) {
    document.getElementById("myText").value = e.target.value;
}

JavaScript (this doesn't work):

function myFunction(e) {
    document.getElementById("myText").value = e.target.options[event.target.selectedIndex].dataset.adr;
}

The second JavaScript example works, but only if I don't use the class="select" tag on the selection. So there must be something in the CSS that could interfere with the JavaScript part?

Is there another method to get the data tag from the selected item?

Upvotes: 2

Views: 2528

Answers (1)

Spectric
Spectric

Reputation: 31987

Pass in the select as the parameter, then do select.options[select.selectedIndex] to get the element. This limits the amount of code needed for the job. The rest is self explanatory.

function myFunction(e) {
  document.getElementById("myText").value = e.options[e.selectedIndex].getAttribute("data-adr");
}
<select class="select" id="test " name="" onchange="myFunction(this)">
  <option disabled selected>Choose Database Type</option>
  <option data-adr="xyz" value="id1">Test name1</option>
  <option data-adr="fsd" value="id2">Test name2</option>
  <option data-adr="sss" value="id3">Test name3</option>
</select>

<input class="form-control" id="myText" type="text" value="-">

Upvotes: 3

Related Questions