Link to home
Start Free TrialLog in
Avatar of badwolfff
badwolfffFlag for United Kingdom of Great Britain and Northern Ireland

asked on

How do I handle multiple selects in jQuery?

I have written a piece of code that synchronizes two select dropdowns. If I choose value one in one select then the same value gets selected in the other select.

https://jsfiddle.net/lupocatttivo/q9tpLxw8/

However, what I would like to do is the exact opposite. If I choose value one in select 1, then in select 2 it should choose value 2. And vice versa.

could anyone please help?

thanks
Avatar of Rob
Rob
Flag of Australia image

I had to add values to your options to make it work: https://jsfiddle.net/q9tpLxw8/1/

<select id="selectOne" class="selectBoxGroup">
    <option value="false">Value One</option>
    <option value="true">Value Two</option>
</select>

<select id="selectTwo" class="selectBoxGroup">
    <option value="true">Value One</option>
    <option value="false">Value Two</option>
</select>

Open in new window


$(document).ready( function() {
    
    $(document).on('change', '.selectBoxGroup', function() {
        $('.selectBoxGroup').val($(this).val());
    });
    
});

Open in new window

Avatar of badwolfff

ASKER

Hi,

thanks for the answer. I already knew this method but the problem is that I can't specify the values beforehand as they are assigned. All I know is that when value 1 of dropdown 1 is chosen, then value 2 of dropdown 2 should become selected. And vice versa. Is it possible without using this trick? All we know is that the number of options per dropdown is always 2.

thanks
There needs to be a value to compare or you can compare it using the selectedIndex property of the select

Open in new window

"or you can compare it using the selectedIndex property of the select "

could you please explain with an example?
ASKER CERTIFIED SOLUTION
Avatar of Rob
Rob
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial