Search code examples
javascriptjqueryhtmlhtml-escape-characters

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>

Solution

  • 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/