Jquery on("click") don't work when selecting text from dropdown-menu

I'm using dropdown-menu from bootstrap and using jquery for changing the dropdown text on selection. The problem comes when a dropdown-menu is created dynamically using jquery it don't change the text of dropdown-menu on selection but it do change when the same action is performed on static html which is already present in HTML below is the code..

<script>
 $(document).ready(function(){
      $(".btn-primary").on("click",function(){
      var htmltxt='<div class="dropdown"><button class="btn btn-default dropdown-toggle changetext" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">Datatypes <span class="caret"></span></button><ul class="dropdown-menu scrollbar" aria-labelledby="dropdownMenu1"><li><a>Boolean</a></li><li><a>Character</a></li></ul></div>';
      $("body").append(htmltxt);
      });
 });
 $(".dropdown").ready(function(){
      $(".dropdown-menu li a").on("click",function(){
           var caret=' <span class="caret"></span>';
           $($(this).closest(".dropdown").find("button")[0]).text($(this).text()).append(caret);
      });
 });

<body>
 <div class="btn btn-primary"> Add DropDrop</div>
 <br></br>
  <div class="dropdown">
 <button class="btn btn-default dropdown-toggle changetext" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">Datatypes <span class="caret"></span></button>
 <ul class="dropdown-menu scrollbar" aria-labelledby="dropdownMenu2">
      <li><a>Boolean</a></li>
      <li><a>Character</a></li>
 </ul></div>
 </body>

The first dropdowm-menu id="dropdownMenu2" works correctly but the second menu id="dropdownMenu2" which is appended from jquery (js variablehtmltxt) will to respond to the on() event.

Answers 1

  • Change:

    $(".dropdown-menu li a").on("click",function(){ 
    

    To:

    $(document).on("click", ".dropdown-menu li a", function(){ 
    

Related Articles