Search code examples
javascriptjqueryhtmljquery-after

jquery elements that were added with .after() method do not trigger events


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.


Solution

  • 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');
    });