JeffVader
JeffVader

Reputation: 702

Jquery - Calling a Function from a button created with a function

this works in Jquery :

<input type="button" class="go" value="GO" />

$(".go").click(function() {
$("#test").html("TEST TEST TEST");
});

But if I try to access the go function from a button created using the following it fails.

$(".new").click(function() {
$.ajax({
        url: $(this).attr("data-value"),
        success: function(data, textStatus, xhr) {
        $('#DIV').html('<input type="button" class="go" value="go" />');
    }
}
 });
});

This code is used when another function click function completes.

Any reason why ?

Thanks

Upvotes: 0

Views: 81

Answers (1)

Satpal
Satpal

Reputation: 133403

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

As you are creating button dynamically.

You need to use Event Delegation. You have to use .on() using delegated-events approach.

i.e.

$(document).on('event','selector',callback_function)

Ideally you should replace document with closest static container.

Example

$('#DIV').on('click', '.go', function () {
    //Your Code     
});

Upvotes: 1

Related Questions