0

When I click the All button below, it is not transferring all the values to another multiple select form? Am I missing something here? Need help.

function transferSelected(fromSelectId, toSelectId) {
  var fromSelect = document.getElementById(fromSelectId);
  var toSelect = document.getElementById(toSelectId);

  for (var i = 0; i < fromSelect.options.length; i++) {
    if (fromSelect.options[i].selected) {
      toSelect.add(fromSelect.options[i]);
    }
  }
}

function transferAll(fromSelectId, toSelectId) {
  var fromSelect = document.getElementById(fromSelectId);
  var toSelect = document.getElementById(toSelectId);

  for (var i = 0; i < fromSelect.options.length; i++) {
    toSelect.add(fromSelect.options[i]);
  }
}
.select-container {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  margin: 10px 0;
}

select {
  width: 200px;
  height: 150px;
  margin: 0 10px;
  resize: none;
  font-size: 1.2em;
  background-color: #f7f7f7;
  border: 1px solid #ddd;
  border-radius: 5px;
}

button {
  font-size: 1.5em;
  padding: 5px;
  border: none;
  background-color: #007bff;
  color: #fff;
  cursor: pointer;
  margin-bottom: 5px;
}

.arrow {
  margin: 0 10px;
  font-size: 1.5em;
  color: #007bff;
}
<div class="select-container">
  <div>
    <h3>Select 1</h3>
    <select id="select1" multiple>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
      <option value="4">Option 4</option>
      <option value="5">Option 5</option>
    </select>
    <br>
    <button id="btn1to2" onclick="transferSelected('select1', 'select2')">→</button>
    <button id="btn1AllTo2" onclick="transferAll('select1', 'select2')">→ All</button>
  </div>
  <div>
    <h3>Select 2</h3>
    <select id="select2" multiple>
      <option value="6">Option 6</option>
      <option value="7">Option 7</option>
      <option value="8">Option 8</option>
      <option value="9">Option 9</option>
      <option value="10">Option 10</option>
    </select>
    <br>
    <button id="btn2to1" onclick="transferSelected('select2', 'select1')">←</button>
    <button id="btn2AllTo1" onclick="transferAll('select2', 'select1')">← All</button>
  </div>
</div>

Wanted to implement this to handle multiple selected options, rarely see this type of form and not sure on how to implement this, any suggestions on how you do this would be really appreciated.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Aaron Magpantay
  • 405
  • 1
  • 5
  • 17
  • When you transfer the first one, `fromSelect.options.length` is reduced by 1 and the indexes of all of the options are reduced by one. Thus you miss the second option. – Heretic Monkey Mar 29 '23 at 00:16
  • See also [Can't remove elements in a select menu.](https://stackoverflow.com/q/41963083/215552) – Heretic Monkey Mar 29 '23 at 00:24

0 Answers0