Avatar of Member_2_1242703
Member_2_1242703
 asked on

Javascript: Setting a dropdown based on another dropdown selection

I have 2 dropdowns, mySelect and myMins

When a selection is made from mySelect, I want to check and see if it is the last option in the list. If it is, I want to set myMins to the first option and disable it. If not, enable myMins.

How would I do this?
JavaScriptjQueryWeb DevelopmentBootstrap

Avatar of undefined
Last Comment
Julian Hansen

8/22/2022 - Mon
Julian Hansen

The principle of linking dropdowns is explained in this article
https://www.experts-exchange.com/articles/28828/Creating-linked-dropdowns-using-jQuery-and-PHP.html

For your specific requirement you need to attach an event handler to the first drop down
HTML
<select name="mySelect" id="mySelect">
    <option value="">Choose</option>
    <option value="somevalue1">SomeValue1</option>
    <option value="somevalue2">SomeValue2</option>
    <option value="somevalue3">SomeValue3</option>
</select>
<select name="myMins" id="myMins">
    <option value="">Choose</option>
    <option value="minsvalue1">MinsValue1</option>
    <option value="minsvalue2">MinsValue2</option>
    <option value="minsvalue3">MinsValue3</option>
</select>

Open in new window

<script>
var lastval = $('#mySelect option:last-child').val();
var firstval = $('#myMins option:eq(1)').val();

$(function() {
  $('#mySelect').change(function() {
    if (this.value == lastval) {
      $('#myMins').val(firstval).prop({disabled: true});
    }
    else {
      $('#myMins').val('').prop({disabled: false});
    }
  });
});
</script>

Open in new window


Working sample here
Member_2_1242703

ASKER
Ok, this was kind of inline with what I was trying. I think my problem is that mySelect is populated by other selections made by the user.
So this is what the HTML looks like even when filled with selections:
<select id="mySelect" name="Hour" required="required"></select>

Open in new window


Is there still a way to do this?
ASKER CERTIFIED SOLUTION
Julian Hansen

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Member_2_1242703

ASKER
Fantastic. Thank you!
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Julian Hansen

You are welcome.