Why won’t this jQuery code work?

jQuery('a#add_media').click(function() {
    input_code="<p>" +
        '<input id="upload_image-' + i + '" type="text" size="36" name="upload_image" value="" />' +
        '<input id="upload_image_button-' + i + '" type="button" value="Upload Image" />' +
        '</p>';
    jQuery(input_code).appendTo('#upload_wrapper');
    i++;
});

jQuery('[id^="upload_image_button"]').click(function() {
    ...
});

Okay, here’s your basic problem.

The first bit of the code adds a function to the click handler on the add_media link, which adds another bit of input HTML code to the page.

The second bit of the code adds a function to the click handler of anything starting with the upload_image_button ID’s.

The problem is that you’re misunderstanding how javascript works in the DOM.

At the time that the above code runs, only two things are happening:
a) The a#add_media button is getting its click handler modified, and
b) Any element in the DOM starting with upload_image_button is getting its click handler modified.

However, the inputs that you’re adding later aren’t in the DOM yet. They don’t exist as elements on the page… yet. So when you add them to the page later, they don’t have the modified click handlers.

jQuery().click() is a direct modification to the DOM. It’s modifying the elements specified, but it’s not retroactive. Adding things to the page later doesn’t make it magically reverse time and add the functions to the new elements added to the page.

To fix it, you need to modify your code to have it add your click handler to the newly created elements as well, after you append them to the upload_wrapper.

Also, your inputs all have the same name=”upload_image” bits, which won’t work if you’re trying to save that resulting information later. name=”upload_image[]” will work though, because of PHP array handling.