简体   繁体   中英

Javascript | Copy selected items from listbox to textarea

I know this is silly question but I am new to Javascript.

I have the following listbox:

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

Under the listbox there is a textarea:

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

And underneath the textarea is a button:

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

I am wondering if it is possible to copy the items that are selected in the listbox to the textarea when the user presses on the button using Javascript.

Note that the listbox has the multiple attribute so that the user can select more than one item.

Any help is greatly appreciated.

Yes it is possible, you should use jQuery though to make it easier:

$("#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
    });
});

Here is the solution using core HTML and 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM