Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

javascript - How to swap values in select lists with jquery?

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".

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

Here is the HTML code:

<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>

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Something like this will work:

$("#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);
});?

Here is your fiddle, updated

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...