Godzilla74 Godzilla74 - 1 month ago 10
HTML Question

Adding multiple select options with jquery

I've created functionality to move items from the left -> right, and vice versa. On top of that, I am added the

option
values of each item into a hidden input box, so I can later submit it to the server for processing. It seems that when I try to add more than one item at a time, only the first one is being added to the hidden input box though.

In the end, my hidden input field should look like:
3233,2332,3234,1212,112


Since I'll accept the parameters in the Ruby on Rails server side to parse and do whatever to (unless there's a better option).

Here's my current code:



$("#btnLeft").click(function(){
var selectedItem = $("#hosts_assigned option:selected");
$("#hosts_available").append(selectedItem);
$("#hosts").remove(selectedItem.val());
});

$("#btnRight").click(function(){
var selectedItem = $("#hosts_available option:selected");
$("#hosts_assigned").append(selectedItem);
var current_hosts = $("#hosts").val();
$("#hosts").val(current_hosts + "," + selectedItem.val());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="hosts_available"size="30" multiple="multiple">
<option value="1222">1.1.2.2</option>
<option value="1232">1.1.2.2</option>
<option value="1242">1.1.2.2</option>
<option value="1252">1.1.2.2</option>
</select>

<select id="hosts_assigned" size="30" multiple="multiple">
<option value="1111">1.1.2.1</option>
</select>

</form>

<button type="button" id="btnRight">&gt;&gt;</i></button>
<br/>
<button type="button" id="btnLeft">&lt;&lt;</i></button>

<br/><br/>
<input type="text" id="hosts" />




Answer

You are getting more than one.

You need to loop:

$("#btnLeft").click(function() {
  $("#hosts_assigned option:selected").each(function() {
    $("#hosts_available").append(this);
  })
});

$("#btnRight").click(function() {
  var current_hosts = $.trim($("#hosts").val()).split(",");
  $("#hosts_available option:selected").each(function() {
    $("#hosts_assigned").append(this);
    current_hosts.push($(this).val());
  });  
  $("#hosts").val(current_hosts.join(","))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <select id="hosts_available" size="30" multiple="multiple">
    <option value="1222">1.1.2.2</option>
    <option value="1232">1.1.2.2</option>
    <option value="1242">1.1.2.2</option>
    <option value="1252">1.1.2.2</option>
  </select>

  <select id="hosts_assigned" size="30" multiple="multiple">
    <option value="1111">1.1.2.1</option>
  </select>

</form>

<button type="button" id="btnRight">&gt;&gt;</i>
</button>
<br/>
<button type="button" id="btnLeft">&lt;&lt;</i>
</button>

<br/>
<br/>
<input type="text" id="hosts" value="" />