jwillis0720 jwillis0720 - 3 months ago 11
jQuery Question

jquery- button to remove all options from one selection and add to another selection

I have the following

<div class="container-fluid" style="padding-left:32px">
<div class=container-fluid>
<select id="leftValues" size="10" multiple>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</div>
<div class="container-fluid center">
<input type="button" id="btnLeft" value="&lt;&lt;" />
<input type="button" id="btnRight" value="&gt;&gt;" />
</div>
<div class='container-fluid'>
<select id="rightValues" size="10" multiple></select>
</div>
</div>

<script language='javascript'>
$("#btnLeft").click(function() {
var values = $("#rightValues>option").map(function() { return $(this).val(); });
$.each(values, function(key, value) {
$('#leftValues')
.append($("<option></option>")
.attr("value",key)
.text(value));
});

$('#rightValues').html('');
});

$("#btnRight").click(function() {
var values = $("#leftValues>option").map(function() { return $(this).val(); });
$.each(values, function(key, value) {
$('#rightValues')
.append($("<option></option>")
.attr("value",key)
.text(value));
});

$('#leftValues').html('');
});
</script>


This is currently functional but seems like a terribly inefficient way to remove all options from one selection to move them to other. Is there an easier way to do this in Jquery (perhaps pure JS)?

Answer

Small note: The code provided in the question actually doesn't work quite correctly...it transfers the indexes instead of the values of the column ;)

You can simplify your JS in this case to:

  $("#btnLeft").click(function() {
    $('#leftValues').html($('#rightValues').html());
    $('#rightValues').html('');
  });

  $("#btnRight").click(function() {
    $('#rightValues').html($('#leftValues').html());
    $('#leftValues').html('');
  });

Here's a fiddle with that code in play.