如何使用jQuery交换选择列表中的值? [英] How to swap values in select lists with jquery?

查看:102
本文介绍了如何使用jQuery交换选择列表中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个简单的选择列表,想添加一个选项以交换其中的值.因此,有第一个带有e的列表. G.值为一个",另一个列表的值为两个".当您单击交换"按钮时,第一个应具有值"TWO",第二个应具有值"ONE".

I have two simple select lists and want to add an option to swap values in them. So, there is the first list with e. g. value "ONE" and the other list has value "TWO". When you click "swap" button, the first one should have the value of "TWO" and the second one should have the value "ONE".

这是jsFiddle: http://jsfiddle.net/YPyRF

Here is jsFiddle: http://jsfiddle.net/YPyRF

这是HTML代码:

<div class="form-item-from">
  <label for="form-item-from">From </label>
 <select class="form-select" id="form-item-from"><option value="ONE">ONE</option></select>
</div>

<div class="form-item-to">
  <label for="form-item-to">From </label>
 <select class="form-select" id="form-item-to"><option value="TWO">TWO</option></select>
</div>

<a href="">Swap values</a>

这是js代码(来自是否有本机jQuery功能来切换元素?):

Here is js code (from Is there a native jQuery function to switch elements?):

jQuery("#form-item-from").after(jQuery("#form-item-to"));

但是,在这种情况下这是行不通的.此外,该功能不应取决于选择列表或交换按钮的位置(我发现了一种解决方案,其中交换按钮必须位于两个列表之间).

However, this is not working in this case. Additionally, the function shouldn't be dependant on the position of select lists or swap button (I found one solution where the swap button has to be between two lists).

推荐答案

类似的方法将起作用:

$("#SwapButton").click(function(e) {
    e.preventDefault();//This prevents the A tag from causing a page reload

    //Get the values
    var fromVal = $("#form-item-from option:selected").val();
    var fromText = $("#form-item-from option:selected").text();
    var toVal = $("#form-item-to option:selected").val();
    var toText = $("#form-item-to option:selected").text();

    //Set the values
    $("#form-item-from option:selected").val(toVal);
    $("#form-item-from option:selected").text(toText);
    $("#form-item-to option:selected").val(fromVal);
    $("#form-item-to option:selected").text(fromText);
});​

这是您的小提琴,已更新

注意:这只会切换选择的option项目.如果这不是您想要的,那么我会误会了,您最好使用亚当的解决方案. 这是一个更好的示例,说明了它仅交换所选值的事实.

NOTE: This will only switch the option items that are selected. If this is not what you want then I have misunderstood and you may be better to use Adam's solution. Here is a better example that illustrates the fact it only swap the selected values.

这篇关于如何使用jQuery交换选择列表中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆