2

I have a page that displays a button up top with id=button-link. Just after the button there's another div with id of display-content. Upon clicking the button, I'm making an AJAX call that pulls up some content and displays it in the second div. Here's the JavaScript code that I'm using:

$('#button-link').click(function(event) {
    event.preventDefault();
    $.ajax({
        url: 'site/someAction',
        success: function(result) {
            $('#display-content').html(result);
        }
    });    
});

$('#secondButton').click(function(event) {
    event.preventDefault();
    $.ajax({
        url: 'site/anotherAction',
        success: function(result) {
            $('#display-content').html(result);
        }
    });    
});

This works exactly as intended and I'm loading some text and HTML elements in the #display-content div. One of those elements is another button with id #secondButton. When the user clicks that second button, I want to make another AJAX call to a different place and pull different content to display in the #display-content div. This, however, does not work. The jQuery script is on the page, it's loading correctly and the HTML elements are also properly displayed on the page after the first AJAX call but it seems that the #secondButton is not part of the DOM and the click events are not triggered when clicked upon it.

Any idea what is going wrong and how can I register click events for this dynamically added button?

1 Answer 1

4

You need to use event delegation.

Note: If the element #secondButton can be added multiple times, this doesn't work. You need to use class for that situation.

For jQuery 1.7 and +

$(document).on('click','#secondButton',function(event) {
    event.preventDefault();
    $.ajax({
        url: 'site/anotherAction',
        success: function(result) {
            $('#display-content').html(result);
        }
    });    
});

For versions before jQuery 1.7

$(document).delegate('#secondButton', 'click',function(event) {
    event.preventDefault();
    $.ajax({
        url: 'site/anotherAction',
        success: function(result) {
            $('#display-content').html(result);
        }
    });    
});
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, that works and as mentioned in the description, it covers elements added in the future as well. Thank you!
@mmvsbg Note: If the element #secondButton can be added multiple times, this doesn't work. You need to use class for that situation. Because id is supposed to be unique in a page.
Yes, well aware of that, I'll make sure to have only one #secondButton id. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.