Igor Ostapiuk Igor Ostapiuk - 25 days ago 6
Ajax Question

Can't work with object after sending it via Ajax request

I sent to my bootstrap modal this content with Ajax:

<div class="list-of-players text-center">
<div class="list">
@foreach($team->players as $player)
<a class="player_choose" id="player_id_Standard_{{$player->id}}">
<div class="player">
<span class="p_name"><span class="flag-icon {{$player->nationality->flag}}"></span> {{$player->fullname}}</span>
</div>
</a>
@endforeach
</div>
</div>


But then when I want to choose some element of this modal window by this code:

$('.player_choose').click(function () {
$('.modal').modal('hide');
});


It doesn't work. What can be a problem? Maybe js don't see "player_choose" elements after ajax?

Answer Source

Yes. Your script executes before you get this element with ajax. You should use event delegation. This should work:

$(document).on('click','.player_choose', function () {
    $('.modal').modal('hide');
});