Javascript |将所选项目从列表框复制到文本区域

Javascript | Copy selected items from listbox to textarea

我知道这是个愚蠢的问题,但我是 Javascript 的新手。

我有以下列表框:

<select id = 'data' multiple='multiple'>
    <option>test@email.com</option>
    <option>test@email.com</option>
    <option>test@email.com</option>
    <option>test@email.com</option>
    <option>test@email.com</option>
 </select>

列表框下有一个文本区域:

<textarea id = 'copydata'>
</textarea>

文本区域下方是一个按钮:

<button id = 'add'>add email</button>

我想知道当用户使用 Javascript.

按下按钮时,是否可以将列表框中 selected 的项目复制到文本区域

请注意,列表框具有 multiple 属性,因此用户可以 select 多个项目。

非常感谢任何帮助。

是的,这是可能的,但您应该使用 jQuery 以使其更容易:

$("#add").click(function(){ // This event fires when you click the add button
    $("#data option:selected").each(function(){ // Loop through each selected option
        $("#copydata").val($("#copydata").val() + $(this).text() + "\n"); // Add its innerhtml to the textarea
    });
});

这是使用核心 HTML 和 Javascript 的解决方案。

<html>
<head>
<script type="text/javascript">

function copyDataToTextArea() {
   var _data = document.getElementById("data");
   var _textArea = document.getElementById("copydata");
   var _selectedData="";

   for(i=0; i<document.getElementById("data").length; i++) {
    var _listElement = document.getElementById("data")[i];
    if(_listElement.selected) {
       _selectedData = _selectedData + _listElement.value + "\n";
    }
   }
   _textArea.value=_selectedData;
}
</script>
</head>
<body>
    <select id='data' multiple='multiple'>
       <option>test1@email.com</option>
       <option>test2@email.com</option>
       <option>test3@email.com</option>
       <option>test4@email.com</option>
       <option>test5@email.com</option>
 </select>
 
 <textarea id='copydata'>
 </textarea>

 <button id ='add' onclick="copyDataToTextArea()" >add email</button>
</body>
</html>