1

I am updating a select element in a modal with JQuery. If I do a console.log, the element exists. enter image description here

If I inspect element, it doesn't exist.

enter image description here

What could be causing the problem? The console.log is occurring after the JQuery has run which means it is working properly. If you don't do it in a modal, the code works fine, but if you do it in a modal, it doesn't append.

What could bring about this behavior?

Here is a sample code that works just fine but doesn't work in my computer.

var options = {
'option1': {'display': 'Series A', 'optionsB': {'name': 'John', 'city': 'Doe'}},
'option2': {'display': 'Series B', 'optionsB': {'name': 'Jane', 'city': 'Maria'}},
}
function updateOptions(){
   /* var options = $('#selectoptions').data('datasets') */;
   for (const opt1 in options) {
       $('#option1').append($('<option>', {
         value: opt1,
         text: options[opt1]['display']
          }))
        }
   
   $('#option1').on('click', function(){
   var option1 = $('#option1').val();
     for (const opt2 in options[option1]['optionsB']) {
         $('#option2').append($('<option>', {
           value: opt2,
           text: options[option1]['optionsB'][opt2]
            }))
          }
      })
}
$(function(){
updateOptions();
});
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
<button type="button" id="examPle" data-bs-toggle="modal" data-bs-target="#exampleModal" class="btn btn-primary">Get Example</button>

<div id="exampleModal" class="modal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Example Modal</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form class="form" id="exampleform" name="exaple" method="post" required> 
          <div id="selectoptions">
            <select id="option1" class="form-select form-select-sm mb-1">
              <option value="...">Select Option 1</option>
            </select>
            <select id="option2"  class="form-select form-select-sm mb-1">
              <option value="...">Select Option 2</option>
            </select>
         </div>
       </form>
     </div>
    </div>
  </div>
</div>

This is an edit to the question: The code above shows a minimal version. The whole code is a django application. I will edit the above html code to be

<div class="modal-body">
    <!-- {% csrf_token %} -->
    <p>Filter Collection</p>
    <div id="navpanel" data-datasets="{{ datasets }}">
    <select id="option1" class="form-select form-select-sm mb-1">
        <option value="...">Select Map Type</option>
    </select>
    </div>
</div>

The python views.py file has the following:

from .controls import datasets
import json
def maps(request):
    context = {
        'datasets': json.dumps(datasets),
    }
    return render(request, 'example.html', context)

The .controls sample is as follows

datasets = {
    'series1': {
        'display': 'This first Text',
        'options': {
            'series1A': {
                'display' : 'This text for 1 A'
            },
            'series1B': {
                'display' : 'This text for 1 B'
            },
        },
     },
'series 2': {
        'display': 'This text',
        'options': {
            'series2A': {
                'display': 'This next text of 2 A',
                   },
            'series2B': {
                'display': 'This next text of 2 B'
                  },
               },
            },
}

And the javascript, you remove the var option variable and you changes it as follows:

function updateOptions(){
       var options = $('#selectoptions').data('datasets');
       for (const opt1 in options) {
           $('#option1').append($('<option>', {
             value: opt1,
             text: options[opt1]['display']
              }))
            }
       
       $('#option1').on('click', function(){
       var option1 = $('#option1').val();
         for (const opt2 in options[option1]['optionsB']) {
             $('#option2').append($('<option>', {
               value: opt2,
               text: options[option1]['optionsB'][opt2]['display']
                }))
              }
          })
    }
    $(function(){
    updateOptions();
    });
Kimlotte
  • 55
  • 6
  • `"Uncaught TypeError: Cannot read properties of undefined (reading 'optionsB')"` – Lee Taylor May 15 '22 at 15:07
  • @LeeTaylor That comes about if you first click the first option. Once you select one of the option, then optionB value becomes available and should populate the second select element adequately. – Kimlotte May 15 '22 at 15:11
  • Your second ss shows "select map type" but your code does not have a "select map type" - so either you have multiple `select` with the same `id` or the code you've provided doesn't match what you actually have (as it's a derived example), in which case, there's no way we can know what you *do* have as it's not the same, so no way for us to guess what might be wrong with your actual code if the code (that's different) that you've provided works fine. – freedomn-m May 15 '22 at 16:32
  • @freedomn-m I have made the changes for the correct code as it runs in the Django project – Kimlotte May 15 '22 at 17:22
  • @Kimlotte I guess you're not reading the object properties correctly `options.option1.optionsB` instead of `options[option1]['optionsB']` and `options.option1.optionsB[opt2]` instead of `options[option1]['optionsB'][opt2]` the result is weird though, is that ok?. – user2495207 May 16 '22 at 15:47
  • @user2495207 well that might be the case here, the truth of the matter, that is not the issue. My problem is the fact that the select document doesn't populate on the modal. If you console.log(), the select document is updated, however when you inspect the element, the populated elements are not there. I would need help with addressing this behavior. – Kimlotte May 18 '22 at 14:29

1 Answers1

0

The answer is there was another element with the same Id. It was updating that one but not the one in the modal.

Kimlotte
  • 55
  • 6
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 19 '22 at 02:19