Vidit Vidit - 2 months ago 11
HTML Question

How do I add multiple values from a select listbox to another listbox on click of a button using javascript function?

I want to select multiple values from first list and on clicking button those values are added to second list. How do I write such function?



function Add() {
//function here

}

<table border="1" align="center">
<tr>Add multiple items at once:</tr>
<tr>
<td>
<select id="li1" size="5" multiple>
<option value="Item1">I1</option>
<option value="Item2">I2</option>
<option value="Item3">I3</option>
<option value="Item4">I4</option>
<option value="Item5">I5</option>
</select>
</td>
<td>
<select id="li2" size="5" multiple>
<!-- add items in here -->
</select>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button type="button" onclick="Add()">Add</button>
</td>
</tr>
</table>




Answer

What did you try ? :-)

var src = document.getElementById("src");
var dst = document.getElementById("dst");

// you can replace the "change" event with any event,
// the related action remains the same (i.e. copy the
// selected options to the second list)

src.addEventListener("change", function () {
  // empty the second list
  while (dst.firstChild) {
    dst.removeChild(dst.firstChild);
  }
  // copy selected options to the second list
  for (var i = 0; i < src.options.length; i++) {
    if (src.options[i].selected) {
      dst.appendChild(src.options[i].cloneNode(true));
    }
  }
});
<select id="src" multiple>
  <option>one</option>
  <option>two</option>
  <option>three</option>
  <option>four</option>
  <option>five</option>
</select>
<select id="dst" multiple></select>

If you worry about browsers compatibility, here is an equivalent using JQuery :

var src = $("#src");
var dst = $("#dst");

src.change(function () {
  dst.empty().append(
    src.find(":selected").clone()
  );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="src" multiple>
  <option>one</option>
  <option>two</option>
  <option>three</option>
  <option>four</option>
  <option>five</option>
</select>
<select id="dst" multiple></select>

Comments