Trung Tran
Trung Tran

Reputation: 13721

Clicking dynamically created buttons jQuery

I have a jQuery datatable where each row has an add to cart button. If I perform a search or I click on another entry of pages in the table, the table will dynamically load new rows & buttons. Therefore, I have two types of add to cart buttons - one for the dynamically created buttons and one for the original buttons:

Click event for dynamically created buttons:

$(document).on('click', 'button.btn.btn-primary.addtocart', function() {
    //add to cart
});

Click event for original buttons:

$(".addtocart").click(function() {
    //add to cart
});

The problem I'm having is if I click the original buttons, the click event fires twice. Does anyone know of a strategy or work around for this?

Upvotes: 0

Views: 896

Answers (2)

S M Abrar Jahin
S M Abrar Jahin

Reputation: 14578

It is a easy solution.

Just use on method in jQuery.

$(document).ready(function(){
    $("dynamically_created_element_selector").on("click", function()
    {
        //do whatever u want
    });
});

Demo is here-

$(function(){
    $('button').on('click',function(){
        var r= $('<br/><button class="dynamic_button" type="button">Dynamic Button</button>');
        $("body").append(r);
    });
    
    $(document).on('click', 'button.dynamic_button', function ()
    {
        alert("Dynamic Element Clicked !!");
    });
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<body>
    <button>Insert after</button> 
</body>

Upvotes: 0

Tushar
Tushar

Reputation: 87203

Use event.stopImmediatePropagation() in the button click handler to stop event from bubbling.

$(".addtocart").click(function (event) {
    //                          ^^^^^    Pass event object to the callback
    //add to cart

    event.stopImmediatePropagation();
});

EDIT:

If both the handlers are same, I'll suggest to use only a delegated handler for both dynamic and static elements.

$(document).on('click', 'button.btn.btn-primary.addtocart', function () {
    // add to cart
});

Upvotes: 4

Related Questions