NickS
NickS

Reputation: 23

Bootstrap dropdown not firing click event if elements are created in a loop

Im trying to use a normal Bootstrap dropdown menu with links, but I want to fire Jquery code instead of having the link redirect as usual. The list will be dynamically created from a database table.

I can get this working fine if i define the list as below.

$(".sitedropdown").append('<li><a class="sitelink" href="#">s</a></li>');
$(".sitedropdown").append('<li><a class="sitelink" href="#">asd</a></li>');

As soon as i try run a loop though to add the elements, the click event magically stops working.

var obj = $.parseJSON(data);
$.each(obj,function(index,arr){
$(".sitedropdown").append('<li><a class="sitelink" href="#">'+arr.wpname+'</a></li>');
});

I have searched all over for this but cant find anything. Before anyone asks, yes i am using jquerys ON event to deal with dynamically added elements.

Upvotes: 0

Views: 500

Answers (1)

NickS
NickS

Reputation: 23

So then try delegating event: $(".sitedropdown").on("click", ".sitelink", function(e){ >e.preventDefault(); alert("bob");}); – A. Wolff

Wolff got it right off the bat.

Thanks again

Upvotes: 1

Related Questions