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 :
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 );
});