0

I have a Bootstrap dropdown button that is filled like the following:

<ul id="brandselection" class="dropdown-menu">
  <li><a href='#'>Brand1</a></li>
  <li><a href='#'>Brand2</a></li>
</ul>

Then I have the following JS code to dynamically create and fill a second dropdown button depending on the selection of the first:

$(function() {
  $("#brandselection li").click(function(e){
    e.preventDefault();
    $("#model").load("getModelsUL.php?brand=" + encodeURI($(this).text()));
  });
});

The resulting button code is basically the same as the one described above - and is created correctly.

But then, I use the exact same JS function (only the id of the div being different) to react to a click on the second button - and it doesn't even enter the function.

I assume it is a problem with the DOM not being considered, since the second button was created after the initial DOM, but I don't know how to handle it correctly.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Frank H.
  • 3
  • 1

1 Answers1

0

It's just a small change to make this work. Change your code to this...

$(function() {
    $("#brandselection").on("click", "li", function(e){
        e.preventDefault();
        $("#model").load("getModelsUL.php?brand=" + encodeURI($(this).text()));
    });
});

That attaches the click handler to #brandselection but only fires the handler when the selector matches the second parameter of li.

This is event delegation and is for exactly this type of scenario, where you want to code event handlers and forget about them, for a DOM that will change in the future.

Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67
  • The answer solved my problem halfway. Actually, I created the botton itself dynamically, since I only wanted it to be displayed when the selection in the first dropdown was made. That didn't work, also not with the solution described above. I had to create the referenced item at the very beginning and could then dynamically change its content. – Frank H. Nov 03 '17 at 14:14