ABC
ABC

Reputation: 4373

Onclick event on dynamic created anchor tag

I have an anchor tag which created dynamically and this anchor tag has an onclick event like this:

$('#'+educationHistoryId).append("<span>"+degreeTitle+"</span>" +  "<a href='javascript:void(0)' onclick='deleteEducationLevel(" + educationHistoryId + ");'>Delete</a>");

when I click on this anchor I got js error saying:

TypeError: 'click' called on an object that does not implement interface HTMLElement.

I suspect some character escaping issue but unable to resolve.

Added

generated html:

<div id="ff8081814734be020147357beda5002b"><span>A Level</span><a onclick="deleteEducationLevel(ff8081814734be020147357beda5002b);" href="#">Delete</a></div>

Upvotes: 0

Views: 8195

Answers (3)

Alok Swain
Alok Swain

Reputation: 6519

Give the span a class and use event delegation.

You can then bind the click event to a existing parent(I am assuming element with id= "#"+educationHistoryId is existing when the event handler attachment takes place) and then delegate the event to the newly added link.

$("#"+educationHistoryId).on("click", <class>, function(){
 deleteEducationLevel(educationHistoryId);
});

Upvotes: 0

SVSchmidt
SVSchmidt

Reputation: 6527

Is there an actual need to do this with just one line? I'd suggest the following solution:

var $anchor = $(document.createElement("a")).attr("href","javascript:").text("Delete").on("click",function() {
    alert("clicked!");
    alert("educationHistoryId: " + educationHistoryId);
});

$("body").append("<span>" + degreeTitle + "</span> ",$anchor);

This works great: Fiddle

I always try to prevent using inline eventhandlers. It's bad practise in my opinion.

Upvotes: 0

Josh Harrison
Josh Harrison

Reputation: 5994

Try replacing that line with the following, so that the event is bound like this:

var $link = $("<a href='javascript:void(0)'>Delete</a>");

$link.on("click", function() {
    deleteEducationLevel(educationHistoryId);
});

$('#'+educationHistoryId).append("<span>"+degreeTitle+"</span>").append($link);

In my (very reduced) test, this seems to work: http://jsfiddle.net/E7LRt/

Upvotes: 2

Related Questions