Question

Sorry if the question was misleading, I couldn't find a better way to describe my problem. Anyway, here goes:

Suppose I had a button start that initially displays a string for me. Said string (let's call it stringA) is output through jQuery like this:

$(".start").click(function() {
    $(".startButton").hide('slow', function() {
        $("#table1").html(stringA);
    });
});

Alright. Cool. That worked without a hitch. Now inside stringA I have multiple
<span class="optButton">this is a button</span> buttons. I have another onClick handler for my optButton button, and it goes like this:

$(".optButton").click(function() {
    alert("Testing");
    $("#table1").html(stringB);
});

Needless to say, clicking on optButton is supposed to replace the contents of #table1 with stringB. However, when I tried it, it doesn't work. I tried adding alert() to test and see if jQuery managed to select optButton, but it seems that it didn't because I get no popup from the alert() function.

My theory is that since optButton was not part of the original HTML and is within a string stringA, jQuery is unable to select optButton as a result. If this is true, is there a workaround to this issue? If it is not, what is the actual cause of the problem here?

Was it helpful?

Solution

You need to use event delegation since your span element has been dynamically added to the DOM:

$('#table1').on('click', '.optButton', function() {
    alert("Testing");
    $("#table1").html(stringB);
});

This technique will helps you to attach click handler to these newly created span elements.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top