Copy selected multiple values to the textbox from more than one drop down

浪子不回头ぞ 提交于 2020-06-02 13:19:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!