0

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

2
  • Yes. Your code using .click binds only to elements that exist at the time the code is run. You want something like .live (deprecated, but documentation shows current proper methods) which binds to elements that may be created later... Commented Jan 27, 2014 at 19:05
  • possible duplicate of jQuery - Click event doesn't work on dynamically generated elements Commented Jan 27, 2014 at 19:12

1 Answer 1

1

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     
});
Sign up to request clarification or add additional context in comments.

2 Comments

Why is it needed to use event delegation? (I know, but it would be good to explain why in the answer....)
I know the answer. Your additional sentence helps, but doesn't make it as clear as it could be.

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.