0

Ok so I made this post ajax thingy which adds a movie into a div with the following code :

<a href="" class="movie" id="1"><img src="images/movies/1.png"></a>

If I would add this manually into the html the jquery script would work and show 'clicked on 1'.

But if I add the movies from a database with $.post it doesn't detect the click.. What can I do?

Here's the code for the jquery script:

$(function(){
    $('#search').click(function(){
        $.post("search_movie.php", { name : $('#search_crit').val() }, function(data){
            rdata = JSON.parse(data);
            $('#search_result').empty();
            $.each(rdata, function(i){
                $('#search_result').append('<a href="" class="movie" data-id="' + rdata[i]['movie_id'] + '"><img src="images/movies/' + rdata[i]['movie_id'] + '.png"></a>');
            });
        });
    });

    $('.movie').click(function(event){
        event.preventDefault();
        alert('clicked on: ' + $(this).attr('data-id'));
    });
});

Here's the code for the html part:

<!--START Search Form-->
<div id="search_form" class="grid_12">
    <form method="POST" action="">
        <input type="text" id="search_crit">
        <select id="search_type">
            <option value="name"> By Name </option>
            <option value="date"> By Date </option>
        </select>
        <button type="button" id="search"> Search </button>
    </form>
</div>
<!--END Search Form-->

<!--START Search Result-->
<div id="search_result" class="grid_12">
    <a href="" class="movie" data-id="1"><img src="images/movies/1.png"></a>
</div>
<!--END Search Result-->

As you can see I added a movie manually in html and that works... I inspected the other elements added from jquery and they have the class movie and the correct id so I don't know the exact cause. Could you help me?

Andrew V
  • 522
  • 10
  • 24

2 Answers2

2

You are attaching the click handlers before the elements are added to the page. You need to use event delegation.

$("#search_result").on("click", '.movie', function(event){
    event.preventDefault();
    alert('clicked on: ' + $(this).attr('data-id'));
});
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

It sounds like the search results are loaded dynamically correct? If that's the case you'll need to delegate the event handler.

$('#search_result').on('click', '.movie', function(event){
    event.preventDefault();
    alert('clicked on: ' + $(this).attr('data-id'));
});
War10ck
  • 12,387
  • 7
  • 41
  • 54