Pregunta

I have a few drop down menus that, when the right combination of values is selected, another drop down is populated. However, once the third drop down is populated, I'm unable to change the selection and the only option I can select is the first. The dropdown does not change to any other options I select. I'm unsure what I'm doing wrong.

$('select').on('change', function() {
  var firstValue = $('#firstSelection').val();
  var secondValue = $('#secondSelection').val();

  if (firstValue == 1 && secondValue == 2) {
    $('#thirdSelection').html('<option>You</option>' +
      '<option>Have</option>' +
      '<option>Selected</option>' +
      '<option>The</option>' +
      '<option>Right</option>' +
      '<option>Options</option>');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="firstSelection">
  <option value='1'>One</option>
  <option value='2'>Two</option>
</select>
<select id="secondSelection">
  <option value='1'>One</option>
  <option value='2'>Two</option>
</select>
<select id="thirdSelection"></select>

jsfiddle

¿Fue útil?

Solución

Your third select list doesn't retain its selected value because it gets repopulated when any select list is changed (including the third one).

I suggest giving the first two lists a class and responding only to lists with that class:

<select id="firstSelection" class="update">
    <option value='1'>One</option>
    <option value='2'>Two</option>
</select>
<select id="secondSelection" class="update">
    <option value='1'>One</option>
    <option value='2'>Two</option>
</select>
<select id="thirdSelection"></select>
$('select.update').on('change', function () {
    var firstValue = $('#firstSelection').val();
    var secondValue = $('#secondSelection').val();

    if (firstValue == 1 && secondValue == 2) {
        $('#thirdSelection').html('<option>You</option>' +
            '<option>Have</option>' +
            '<option>Selected</option>' +
            '<option>The</option>' +
            '<option>Right</option>' +
            '<option>Options</option>');
    }
});

Working Example (jsFiddle)

Otros consejos

Because you are triggering the event off $("select").change() any time any of the selects change (including the third one) you are repopulating the third one which is forcing the first option to be selected.

All you have to do is change the selector for your event trigger from

$('select').on('change', function () {

to

$('#firstSelection, #secondSelection').on('change', function () {

and it will work as intended.

Here is a working jsFiddle

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top