Richard R. Legaspi
Richard R. Legaspi

Reputation: 21

Onclick function not working on inserted HTML

Im just new to jquery and while doing experimentations on jquery I encountered this problem -> It can insert the html to the div but the click function in not working on the inserted html. Anyone knows why? thanks in advance

$(document).ready(function(){
$("#insertTest").click(function(){
$("#testDiv").html($("#testDiv").html() + '<p><a href="#" class="testClick">Click  Me</a></p>');
});

$(".testClick").click(function(){
alert('Ahoy');
});

});

<a href="#" id="insertTest">Click to Insert</a>
<div id="testDiv">
</div>

Upvotes: 2

Views: 455

Answers (4)

Tats_innit
Tats_innit

Reputation: 34107

here you go: http://jsfiddle.net/Hc7Cc/26/

o well I can see you have enough hint:

here is the working jsfiddle

working demo: http://jsfiddle.net/Hc7Cc/26/

Cheers

Upvotes: 0

xdazz
xdazz

Reputation: 160863

You could use .live, but it is deprecated, use .on instead. And you you could use .append for insert the html.

$("#insertTest").click(function () {
    $("#testDiv").append('<p><a href="#" class="testClick">Click  Me</a></p>');
});

$("#testDiv").on('click', '.testClick', function () {
    alert('Ahoy');
});

Upvotes: 0

Andreas Wong
Andreas Wong

Reputation: 60536

Use .on() method http://api.jquery.com/on/, .live() is deprecated as of 1.7, so to ensure future compatibility, use on() instead of live()

http://api.jquery.com/live/

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

$('.testClick').on('click', function(){
    alert('Ahoy');
});

Upvotes: 2

Austin Brunkhorst
Austin Brunkhorst

Reputation: 21130

Use the method live()

$('.testClick').live('click', function(){
    alert('Ahoy');
});

Edit: to support jQuery 1.7+ standards, use .on() instead of .live()

Upvotes: 1

Related Questions