mySun mySun -4 years ago 104
jQuery Question

How to change selected option element between 2 selectbox in select2 in jQuery?

I need change selected between two select2 with jQuery.

For Example:

<select id="fromCity" class="select2">
<option value='THR' selected> Tehran </option>
<option value='LON'> London </option>


<select id="toCity" class="select2">
<option value='THR'> Tehran </option>
<option value='LON' selected> London </option>

Now, I need after click THR -> LON change to LON -> THR

In jQuery:

$('i[data-change-airport]').on('click', function () {
var fromCity = $('#fromCity').val();
var toCity = $('#toCity').val();

$('#fromCity').select2('val', toCity);
$('#toCity').select2('val', fromCity);

But this code not work. Where is problem?

Answer Source

If you are using one of latest versions > 4.0,

Then try this,

$('i[data-change-airport]').on('click', function () {
    var fromCity = $('#fromCity').val();
    var toCity = $('#toCity').val();

Give it a try, it should work.

if still doesn't work,
you can try one more alternative


This should work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download