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

Categories

0 votes
1.4k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...