user3087370
user3087370

Reputation: 33

exchanging values in a select list with jQuery

I'm trying to swap select option values with jQuery when a links clicked, at the moment its just resetting the select when the links clicked, not sure what's going wrong?:

jQuery:

$(function () {
    $("#swapCurrency").click(function (e) {
        var selectOne = $("#currency-from").html();
        var selectTwo = $("#currency-to").html();
        $("#currency-from").html(selectTwo);
        $("#currency-to").html(selectOne);
        return false;
    });
});

JS Fiddle here: http://jsfiddle.net/tchh2/

Upvotes: 0

Views: 98

Answers (3)

kapa
kapa

Reputation: 78681

I wrote it in a step-by-step way so it is easier to understand:

$("#swapCurrency").click(function (e) {

    //get the DOM elements for the selects, store them into variables
    var selectOne = $("#currency-from");
    var selectTwo = $("#currency-to");

    //get all the direct children of the selects (option or optgroup elements)
    //and remove them from the DOM but keep events and data (detach)
    //and store them into variables
    //after this, both selects will be empty
    var childrenOne = selectOne.children().detach();
    var childrenTwo = selectTwo.children().detach();

    //put the children into their new home
    childrenOne.appendTo(selectTwo);
    childrenTwo.appendTo(selectOne);

    return false;
});

jsFiddle Demo

Your approach works with transforming DOM elements to HTML and back. The problem is you lose important information this way, like which element was selected (it is stored in a DOM property, not an HTML attribute, it just gives the starting point).

Upvotes: 2

George
George

Reputation: 36784

You are replacing the whole HTML (every option) within the <select>. As long as each select has the same amount of options and they correspond to each other, you can use the selected index property to swap them:

$("#swapCurrency").click(function (e) {
    var selOne = document.getElementById('currency-from'),
        selTwo = document.getElementById('currency-to');
    var selectOne = selOne.selectedIndex;
    var selectTwo = selTwo.selectedIndex;
    selOne.selectedIndex = selectTwo;
    selTwo.selectedIndex = selectOne;
    return false;
});

JSFiddle

Upvotes: 0

VisioN
VisioN

Reputation: 145398

That happens because you remove all elements from both <select> fields and put them as new again. To make it working as expected you'd better move the actual elements as follows:

$("#swapCurrency").click(function(e) {
    var options = $("#currency-from > option").detach();
    $("#currency-to > option").appendTo("#currency-from");
    $("#currency-to").append(options);
    return false;
});

DEMO: http://jsfiddle.net/tchh2/2/

Upvotes: 2

Related Questions