Digzol
Digzol

Reputation: 323

jQuery - Swap values between select lists

I have a list of n selects containing values from 1 to n. Whenever I change a value in a select, the other select containing the same value should be swapped to what was previously selected in the first select.

For example, initially listA is set to 1 and listE is set to 5. If listA is changed to 5 then listE should become 1, and the other lists remain unchanged.

This is different from questions such as How to swap values in select lists with jquery? because the values are swapped between multiple dynamic lists instead of between two static lists.

EDIT: Every value should only appear once in the group of lists. They initially all have distinct values.

Here is the code I have so far, needless to say, it does not work :

http://jsfiddle.net/yye3U/

HTML:

<div class="parentdiv">
  <select class="ranking">
    <option value="1" selected>1</option>
    <option value="2">2</option>
    <option value="3">3</option>
  </select>
  <select class="ranking">
    <option value="1">1</option>
    <option value="2" selected>2</option>
    <option value="3">3</option>
  </select>
  <select class="ranking">
    <option value="1">1</option>
    <option value="2">2<option>
    <option value="3" selected>3</option>
  </select>
</div>

JS:

var previous;
$( ".ranking" ).on( "focus", function() {
    previous = $( this ).val();
}).change(function() {
    var value = $( this ).val();
    var parent = $( this ).closest( ".parentdiv" );

    $( ".ranking option[value='" + value + "']", parent ).not( this ).parent().prop( 'selectedIndex', parseInt(previous) - 1 );
});

Upvotes: 2

Views: 1205

Answers (2)

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

By storing the previous value in the data of the DOM element, you can easily do what you want with that simple code :

$(".ranking").each(function(){
    $(this).data('__old', this.value);
}).change(function() {
    var $this = $(this), value = $this.val(), oldValue = $this.data('__old');

    $(".ranking").not(this).filter(function(){
        return this.value == value;
    }).val(oldValue).data('__old', oldValue);

    $this.data('__old', value)
});

Here's a fiddle

Upvotes: 5

a1ee9b
a1ee9b

Reputation: 31

Just add ':selected' to your selector in the last line of your JS:

$(".ranking option[value='" + value + "']:selected", parent).parent().not(this).prop('selectedIndex', parseInt(previous) - 1);

Upvotes: 1

Related Questions