Skip to content
Advertisement

Swap a select text with javascript?

I have a example code here:

function swap() {
  var sel1 = $("#se1 option:selected").text();
  var sel2 = $("#se2 option:selected").text();;
  console.log(sel1, sel2)
  $("#se1").val(sel2);
  $("#se2").val(sel1);
}
<select id="se1">
  <option value="1">DOG</option>
  <option value="2">CAT</option>
  <option value="3">BIRD</option>
</select>
<button onclick="swap()">SWAP</button>
<select id="se2">
  <option value="4">DOG</option>
  <option value="5">CAT</option>
  <option value="6">BIRD</option>
</select>

I want to swap se1 and se2 . Here is my code i tried:

function swap() {
  var sel1 = $("#se1 option:selected").text();
  var sel2 = $("#se2 option:selected").text();;
  console.log(sel1, sel2)
  $("#se1").val(sel2);
  $("#se2").val(sel1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<select id="se1">
  <option value="1">DOG</option>
  <option value="2">CAT</option>
  <option value="3">BIRD</option>
</select>
<button onclick="swap()">SWAP</button>
<select id="se2">
  <option value="4">DOG</option>
  <option value="5">CAT</option>
  <option value="6">BIRD</option>
</select>

It’s work but it require Jquery 1.2.3 but i want to use Jquery 2.1.3. If i change script url to “https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js” but it isn’t work

Thanks for help!

Advertisement

Answer

You shouldn’t be swapping the values or the text of the two selected items in the lists. You just need to swap which item is selected in each list. Once that is done, that option will have whatever value the list has set up for it.

The version of JQuery you use here doesn’t matter since what you are doing requires JQuery operations that have been in JQuery since the beginning.

var sel1 = $("#se1");
var sel2 = $("#se2");
function swap() {
  let selection1 = sel1[0].selectedIndex;    // Store the first list's selection
  sel1[0].selectedIndex = sel2[0].selectedIndex;
  sel2[0].selectedIndex = selection1;
  
  // Test
  console.log(sel1.val(), sel2.val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<select id="se1">
  <option value="1">DOG</option>
  <option value="2">CAT</option>
  <option value="3">BIRD</option>
</select>
<button onclick="swap()">SWAP</button>
<select id="se2">
  <option value="4">DOG</option>
  <option value="5">CAT</option>
  <option value="6">BIRD</option>
</select>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement