Question

This is the code:

<s:file name="upload"  id="upload"></s:file>
  $('input[id^="upload"]').change(function(){
        alert("aa");
        $(this).after('<input type="file" name="upload_3" id="upload_3"/>');
        alert($("#upload_3").attr("name"));
    });
    $('input[id^="upload"]').click(function(){
        alert("click");
    });

When I click "upload" element, it triggers the click and change events, and alerts "aa" and "upload_3". It then added <input type="file" name="upload_3" id="upload_3"/> after the "upload" element in HTML. But when I click the newly added element ("upload_3" element), the click and change even do not trigger.

Was it helpful?

Solution 2

Events are bound to elements while loading the DOM(Static elements). While you are adding some element dynamically you need to attach the events yourself.

Following code will bind a click event to the dynamically added element using bind().

$(this).after('<input type="file" name="upload_3" id="upload_3"/>').bind('click', function(){
    alert('Click event fired for the new element');
});

You can also use on method. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers.

From jquery doc:

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.

$(this).after('<input type="file" name="upload_3" id="upload_3"/>').on('click', function(){
    alert('Click event fired for the new element');
});

OTHER TIPS

You need to attach the event handlers to the dynamically appended elements. Using jQuery, the .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers.

This might help you:

$(document).on('click','input[id^="upload"]',function(){
    alert("click");
});

Also have a look at the documentation.

You need to set up a delegated event handler in this case; this can be done by using .on():

 $('#parent').on('click', 'input[id^="upload"]', function() {
     // do your stuff here
 });

In this case, the #parent node refers to the closest parent of your <input> elements. The click event is first handled by this parent node and then translated before it calls your click handler to make sure this references the correct node.

you can use "on" or "live" for the elements that are added to the DOM on the fly. but "on" is preferred.

$('input[id^="upload"]').change(function(){
    var _this = $(this)
    $('<input type="file" name="upload_3" id="upload_3"/>').insertAfter(_this);
    });

$(document).on('click','input[id^="upload"]',function(){
    // do your stuff
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top