We help IT Professionals succeed at work.

Javascript: Setting a dropdown based on another dropdown selection

590 Views
Last Modified: 2017-03-21
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?
Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
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

Author

Commented:
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?
CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION

Author

Commented:
Fantastic. Thank you!
CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
You are welcome.