Bacon
Bacon

Reputation: 823

Appending To Dynamically Added Elements

I have a div that exists when the page is loaded. I append a button and another to it. I then want to click the button and append things into .

So far the first part is working but I cannot append to any elements that were created dynamically.

$(document).ready(function () {

    // THIS WORKS
    $("#Value").change(function () {
        var value = $("#Value").val();
        $("#Question_Field").empty();
        for (var i = 1; i <= value; i++) {
            $("#Question_Field").append('<input type="button" id="button" /><div id="test"></div>');
        }
    });

    // THIS DOES NOT WORK
    $("#test").click(function () {
        console.log("Click");
        ("#test").append(STUFF);
    });
});

It's not even logging the click.

Upvotes: 0

Views: 476

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074058

There are two main problems.

  1. When you're hooking the event, no #test element exists yet, and so nothing gets hooked up.

  2. You're creating multiple elements with the same id.

Also, your append call is missing a $ at the beginning.

You can fix the first using event delegation (and this code fixes the append as well):

$(document).on('click', '#test', function () {
    console.log("Click");
    $("#test").append(STUFF);
});

That tells jQuery to hook the click event on document, but only fire the handler if the event originated on or passed through an element matching the given selector (#test) as it bubbled up to the document.

To fix the second issue, multiple elements with the same id, you need to change your loop outputting the elements. It could well be that you want to be using a class rather than an id.

Upvotes: 1

Nick Andriopoulos
Nick Andriopoulos

Reputation: 10643

click can only handle elements that exist when it is called. You should check .live() http://api.jquery.com/live/ or .on() http://api.jquery.com/on/ depending on your jQuery version.

Upvotes: 0

Related Questions