I am trying to implement a click event in the bootstrap dropdown menu

Hi, I have a bootstrap popup menu that automatically populates from the database. I try to get an event when I click on one of the items in the menu. I tried

$("body").on("click", ".ddBtnClick", function(event) { console.log("Is it working? Yes!!"); }); 

with ".ddBtnClick" being the class assigned to each of the elements in the list. but nothing happened. Here is the code to populate the list from the database.

 $.getJSON("http://jeremiah.abrahamott.com/DadsCarsObjects.txt", function(data){ $.each(data.aaData, function(i, option){ $("#dropdownfill").append($('<li/>').append($('<a/>').attr("id", option.Year).attr("href", "#").attr("tabindex", "-1").addClass("ddBntClick").text(option.Make))) }); }); 

Here is the html for the dropdown.

 <div class="row" style="margin-left:50px;"> <div class="span3"> <div class="btn-group"> <a class="btn dropdown-toggle" data- toggle="dropdown" href="#">Make <span class="caret"></span> </a> <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu" id="dropdownfill"> </ul> </div> </div> </div> 
+4
source share
2 answers

The problem is with your class name. You register a delegated event handler for ddBtnClick , but the actual class name is ddBntClick .

 $("body").on("click", ".ddBtnClick", function(event) { console.log("Is it working? Yes!!"); }); 

and

 .addClass("ddBntClick"); 

Change the name of the class at build time or change its delegation.

 $(function() { $("body").on("click", ".ddBntClick", function(event) { console.log("Is it working? Yes!!"); }); }); 
+1
source

Have you tried to wrap your Javascript in the document.ready event?

 $(function() { $("body").on("click", ".ddBtnClick", function(event) { console.log("Is it working? Yes!!"); }); }); 

See the jQuery .ready() documentation for more information and examples.

In addition, you must register the click event on the actual button and use .click() instead of .on() :

 $(function() { $(".ddBtnClick").click(function(event) { console.log("Is it working? Yes!!"); }); }); 

In addition, you have a typo :

 .addClass("ddBntClick") 

Must be:

 .addClass("ddBtnClick") 
0
source

Source: https://habr.com/ru/post/1481828/


All Articles