thoslin
thoslin

Reputation: 7019

Javascript doesn't work on ajax generated code?

I'm using jQuery form plugin to upload files. The plugin uses a hidden iframe to

upload without refreshing the page. Everything works fine except javascript doesn't work on

generated code. Here's my code:

    <form id="image_form" action="" method="post" enctype="multipart/form-data">
        <input type="file" id="image_file" name="image_file"><br>
        <input type="submit" value="upload">
    </form>
    <div id="avatar_wrapper">
    </div>

This form uploads an image to server and server will return some processed images.

<script type="text/javascript">
    $(document).ready(function() {
        var options = {
            success: showResponse,
            dataType: 'html'
        };
    $('#image_form').ajaxForm(options);

        $('.choose_avatar').hover(function() { /* Just for test */
            alert('hello');
        });
    });
    function showResponse(responseText, statusText, xhr, $form) {
        $('#avatar_wrapper').append(responseText);
    }
</script>

responseText contains some images.

  <img src="http://localhost/avatar/0.jpg" class="choose_avatar" choice=0>
  <img src="http://localhost/avatar/1.jpg" class="choose_avatar" choice=1>
  <img src="http://localhost/avatar/2.jpg" class="choose_avatar" choice=2>

I wrote these code to test:

$('.choose_avatar').click(function() { /* Just for test */
    alert('hello');
});

It's strange that click function doesn't work on these generated code. Can someone please help me with this?Thanks.

Upvotes: 3

Views: 944

Answers (4)

alex
alex

Reputation: 490123

You will have to use live(), or do it manually, place a click handler on the parent element that is constant, and check event.target to see which one was clicked.

This is how live works under the hood, anyway, so just stick with it :)

Note that if you're using a newer jQuery, then use on() instead of live().

Upvotes: 9

sharat87
sharat87

Reputation: 7526

When you do a $('.choose_avatar'), you are selecting elements with class choose_avatar (which don't exist yet) and attaching the event handler. Which obviously won't work if the elements are loaded dynamically. A more correct approach is to handle the delegated event on the wrapper div like so,

$('#avatar_wrapper').delegate('img.choose_avatar', 'click', function (e) {
    // do stuff
});

Upvotes: 0

capi
capi

Reputation: 1453

On the container avatar_wrapper you must bind a live/delegate listener :

$('#avatar_wrapper').delegate('.choose_avatar','click',function() {
    alert('hello');
});

Hope it helps!

Upvotes: 0

rahul
rahul

Reputation: 187020

You will have to use .live on these dynamically generated elements.

$('.choose_avatar').live("click", function() { /* Just for test */
    alert('hello');
});

Upvotes: 2

Related Questions