交换选择1中的所有选项以选择2

时间:2016-01-20 04:48:36

标签: javascript jquery html

我想在有人点击交换按钮时更改列表的值,我的代码链接为http://codepen.io/varadekd/pen/OMOYpa

HTML

<center>
<table>
  <tr>
    <th>list 1 </th>
    <th> list 2 </th>
  </tr>
  <tr>
    <td>
      <select id="mySelect1" size="5" multiple style="width:200px">
        <option value="opt1">First item of list 1</option>
        <option value="opt2">Second item of list 1</option>
        <option value="opt3">Thrid item of list 1</option>
        <option value="opt4">Fourth item of list 1</option>
        <option value="opt5">Fifth item of list 1</option>
      </select>
    </td>

    <td>
      <select id="mySelect2" size="5" multiple style="width:200px">
        <option value="opt6">First item of list 2</option>
        <option value="opt7">Second item of list 2</option>
        <option value="opt8">Thrid item of list 2</option>
        <option value="opt9">Fourth item of list 2</option>
        <option value="opt10">Fifth item of list 2</option>
      </select>
    </td>
  </tr>
</table> 
</center>
<center>
  <button id="toRight">Swap to list 1</button>

  <button id="toLeft"> Swap to list 2</button> <br/>

  <button id="swipe"> Swap </button>
<input type="button" onClick="count1()" value="Item in list 1" />
<input type="button" onClick="count2()" value="Item in list 2" />
 </center>

JS

    $(function () { 
  function moveItems(origin, dest) {
    $(origin).find(':selected').appendTo(dest);
}

$('#toLeft').click(function () {
    moveItems('#mySelect1', '#mySelect2');
});

$('#toRight').on('click', function () {
    moveItems('#mySelect2', '#mySelect1');
});
});

function count1(){
  var store = $('select#mySelect1 option').length;
  alert(store);
}

function count2(){
  var store2 = $('select#mySelect2 option').length;
  alert(store2);
}

我必须将所有选项从列表1移到列表2,同时将所有选项从列表2移到列表1

2 个答案:

答案 0 :(得分:2)

一种简单的方法是使用JQuery:

$('#swipe').click(function () {

var selOne = $("#mySelect1").html();
var selTwo = $("#mySelect2").html();

$("#mySelect1").html(selTwo);
$("#mySelect2").html(selOne);

});

<强> Working CodePen

答案 1 :(得分:1)

使用你的功能我已经创建了以下函数来交换列表。

$product = GetProduct('SKU03'); $product->setData('cardboard_height_cm', 28.5); $product->setData('cardboard_width_cm', 37); SaveProduct($product); unset($product);

工作Demo

希望这有帮助。

- 帮助:)