0

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?

1
  • Felix answer is right. Since the element .optButton did not exist in the first place, the click handler was binded to nothing. To prevent that, use delegation (= .on). Commented Feb 24, 2014 at 7:55

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Another way would be to add the click listener when the content is added, but this is clearer.
@Felix Thank you so much! 10 internets as well for the link to the documentation!

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.