2

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?

3
  • The second javascript works well. What do you mean? - Even the second javascript works but only if I don't use the class="select" tag on the selection.. Commented Apr 24, 2021 at 20:12
  • is the function myFunction(event) used by different HTML elements ? Commented Apr 24, 2021 at 20:32
  • 2
    e.target.options[event.target.selectedIndex] should be e.target.options[e.target.selectedIndex], by the way. Please see if this fixes your issue Commented Apr 24, 2021 at 20:34

1 Answer 1

3

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="-">

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.