Search code examples
javascriptjquerydropdownhtml-select

Select option in dynamically generated select (dropdown) list


I am using a combination of two dropdown lists (select). Depending on the choice a user makes in the first list, the second one gets populated by a

$("#second-choice").load("textdata/" + $('#first-choice').val() + ".txt") call. Using the same combo of lists in another part of the webpage, I am saving the selections that the user has made as indexes (the first choice gets saved as 0 etc.). I then repopulate and select the user's choice via nth-child(whatIhaveSaved).

What I am unable to do, however, is make this selection in the second list (i.e. it does load the list data, but does not select anything, no matter the value it reads). What can be done about that?

I am unable to add much more code, so in essence what happens and what I want to do is:

 $("#first-choice").change(function() {
        $("#second-choice").load("textdata/" + $(this).val() + ".txt");
    });

All the other settings I want to save, work great by using:

$('#first-choice option:nth('+ parseInt(savedPresets[0]) +')').attr("selected","selected");

Once this setting, for example, gets applied, the second list gets populated as well. However, the following similar call for the second list, seems to be getting ignored.

Unfortunately, I am not much experienced with jQuery


Solution

  • One problem is that load() is an ajax method and ajax is asynchronous.

    this means if you want to interact with the new html you have to do it in the success callback that fires after that html is received

    $("#first-choice").change(function() {
          $("#second-choice").load("textdata/" + $(this).val() + ".txt", function(){    
           // new html exists can work with it here
    
          });
    
         // any code here will run before new html arrives
    })