Link to home
Start Free TrialLog in
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?
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

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
Avatar of Member_2_1242703
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
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa 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
Fantastic. Thank you!
You are welcome.