0

I am using Jquery ajax to get template from Laravel,

        $(".menugroupbutton").on('click', function() {
    
                jQuery.ajax({
                    url: "/menu/renderitems",
                    data: {item_group: this.id },
                    type: "POST",
                    success:function(data){
                        $data = $(data); // the HTML content that controller has produced
                        $('#itemcontainer').hide().html($data).fadeIn();
                    }
                });
            });
        };

Here is HTML which is currently in current blade template,

 <div class="row" style="padding-left: 15px" id="itemcontainer">
  @include('pages.menu.renderitems')
 </div>

the template which going to be rendered on menugroupbutton click is

@foreach($items as $i)
<div class="col-lg-2 bg-light-info px-6 py-8 rounded-xl mr-2 mb-2 click2add">
    <a href="#" class="text-secondary font-weight-bold font-size-h6 itemid" id="{{$i->item_id}}">{{$i->item_name}}</a></br>
    <a href="#" class="text-info font-weight-bold font-size-h6">{{$i->item_price}}</a>
</div>
@endforeach

Here is click2add event,

$('.click2add').on( 'click', function () {
console.log('test');
});

I have one more onclick event on class click2add.

Now problem is,

When first time page is loaded, my click event on class click2add is working fine, means it show test in console But when i render template(which have click2add class) with .menugroupbutton, click2add event is no more working, no console log of test.

How can I make click event working on render template as well?

Thanks,

rjcode
  • 1,073
  • 1
  • 20
  • 43
  • Problem is resolved with binding, [https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – rjcode Dec 04 '20 at 10:31

1 Answers1

0

Your jQuery code should be:

$('#itemcontainer').html($data).fadeIn(); //Remove hide()

Working Fiddle

Hope this will be useful.

Rajen Trivedi
  • 709
  • 1
  • 2
  • 8
  • Hi, No that is not an issue, i have updated the question with click2add event when the page is freshly loaded, it works, but when content is rendered, click2add does not work. – rjcode Dec 04 '20 at 10:23