'Adding Additional information to dropdown box options

I am wanting to add hidden/additional information to a dropdown box. Currently, it works using

javascript

function myFunction() {
  var copyText1 = document.getElementById("ID");
  

  var value = copyText1.value;
  navigator.clipboard.writeText(value);

}  

and html

<select id="ID">
     <option>Call James</option>
     <option>Call Bob</option>
     <option>Call Jane</option>
</select>


<button onclick="myFunction()">Copy number</button>

however, I would like when 'Call James' is selected, the copy number will copy a phone number (eg - '5551234') to the clipboard instead of the text 'Call James'

Any assistance would be much appreciated.



Solution 1:[1]

  • Use the Element's value attribute to store and then retrieve the number
  • Stop using inline on* handlers. Use Element.addEventListener instead.
  • Use type="button" since buttons are by default of type Submit.
const elSelect = document.querySelector("#ID");
const elCopy = document.querySelector("#copy");

const copyNUmber = () => {
  console.log(elSelect.value);
  navigator.clipboard.writeText(elSelect.value);
};

elCopy.addEventListener("click", copyNUmber);
<select id="ID">
  <option value="123456000">Call James</option>
  <option value="654321000">Call Bob</option>
  <option value="999999000">Call Jane</option>
</select>

<button id="copy" type="button">Copy number</button>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Roko C. Buljan