Shawn White
Shawn White

Reputation: 319

Dynamically created anchor links not receiving 'click' events?

I'm using JS to create the HTML below. (It's a bootstrap dropdown button)

<div class="btn-group">
    <button type="button" class="btn btn-default dropdown-toggle my-status" data-toggle="dropdown">
        Status <span class="caret"></span>
     </button>
     <ul class="dropdown-menu status-menu" role="menu">
         <li><a href="#" class="status" data-status-id="0">None</a></li>
     </ul>
</div>

And in JQuery I'm trying to process clicks on the link inside there.

$('li').on('click', 'a.status', function(e) {
    e.preventDefault();
    alert("hi");
});

I've tried about 6 different ways to select those links, but nothing I do seems to be catching it.

Since they're created dynamically, I know I need to use the 'on' function, but it just doesn't seem to be working in the least.

I can get it to work in a JSFiddle, but the code there isn't created dynamically - which is the issue I think.

Is there something stupidly obvious that I'm missing here?

Upvotes: 1

Views: 1473

Answers (5)

Subha
Subha

Reputation: 1051

Why don't you generate the ancor tag with a onclick function?

<li><a href="#" class="status" data-status-id="0" onclick="DoSomething();">None</a></li>
<script>
  function DoSomething(){
    // Do your work
  }
</script>

Hope this helps

Upvotes: 2

tymeJV
tymeJV

Reputation: 104775

If that whole chunk of HTML is dynamic, then you need to target the container that HTML is appended to and use on

$(containerOfAppendedContent).on("click", ".btn-group li a", function() {

Upvotes: 4

Harutyun Abgaryan
Harutyun Abgaryan

Reputation: 2023

Use this change li to document

$(document).on('click', 'a.status', function(e) {
    e.preventDefault();
    alert("hi");
});

Upvotes: 1

Sam Battat
Sam Battat

Reputation: 5745

Make sure you are selecting a static parent, so if li is dynamically created too, use its parent or its parent's parent

$('div.btn-group').on('click', 'ul li a.status', function(e) {
    e.preventDefault();
    alert("hi");
});

if that div is also dynamically created you could go up to the body or even document

$(document).on('click', 'ul li a.status', function(e) {
    e.preventDefault();
    alert("hi");
});

Upvotes: 4

j08691
j08691

Reputation: 207901

Assuming the entire block of code you posted is created dynamically, or even just the list, when you bind events to dynamically added elements, you need to bind to elements that are already in the DOM when the code is executed. Try:

$(document).on('click', 'a.status', function(e) {
    e.preventDefault();
    alert("hi");
});

$(document) is a worst case scenario, so if you have an element closer to the ones being added dynamically that exists when the jQuery is executed, use that over document.

Upvotes: 4

Related Questions