问题
I have tow drop downs as below.
<select id="checkOwner" multiple="multiple" onchange="copyValue1(this)">
<option value="FirstName">First Name</option>
<option value="SecondName">Last Name</option>
</select>
<select id="checkMember" multiple="multiple" onchange="copyValue2(this)>
<option value="FirstName">First Name</option>
<option value="SecondName">Last Name</option>
</select>
I have below javascript to print selected multiple values from dropdowns.
function copyValue() {
var str = "";
for (var option of document.getElementById('checkOwner').options) {
if (option.selected) {
str+= option.value+" ";
}
document.getElementById('mytextbox').value = str;
}
}
function copyValue2() {
var str = "";
for (var option of document.getElementById('checkMember').options) {
if (option.selected) {
str+= option.value+" ";
}
document.getElementById('mytextbox').value = str;
}
}
The problem is when I select values from first that value print in text box. But I select value from second dropdown First printed values disappeared and second dropdown box values are printed. But I want to keep all and when I untick I want to remove this value also. How can I do this.
回答1:
If you accepting duplicate values then, this is the solution:
function copyValue2() {
var old = document.getElementById('mytextbox').value;
var str = "";
for (var option of document.getElementById('checkMember').options) {
if (option.selected) {
str+= option.value+" ";
}
document.getElementById('mytextbox').value = old+" "+str;
}
}
回答2:
Its a typo:
<select id="checkMember" multiple="multiple" onchange="copyValue2(this)>
Should be:
<select id="checkMember" multiple="multiple" onchange="copyValue2(this)">
来源:https://stackoverflow.com/questions/62144811/copy-selected-multiple-values-to-the-textbox-from-more-than-one-drop-down