0

Hi I inject a piece of HTML code dynamically inside a DIV on click using Jquery Ajax. After injecting i am not able to select the elements from this injected HTML. I need to write click events for these elements to change some data on the main page. If i write jquery inline i am not able to access the elements on the main page. Can anyone help?

My Jquery Ajax call

$(".template-2-column-std a").not('.emptyMessage').click(function () {        
    var parentidVal = $(this).data('parentid')
    $.ajax({
        url: '/Navigation/GetBreadCrumbList',
        contentType: 'application/html; charset=utf-8',
        data: { id: parentidVal },
        type: 'GET',
        dataType: 'html'
    })
    .success(function (result) {
        $('#breadcrumb').html(result);
    })
    .error(function (xhr, status) {
        alert(status);
    })
});

3 Answers 3

0

You need to use event delegation to attach event listeners to elements that weren't on the DOM when the document loaded. Try this:

$('#breadcrumb').on('click', <selector>, function() {...});

I'm assuming $('#breadcrumb') exists when the DOM loads. Then you just use to filter its descendants.

1
  • It also works if i place code inside success function
    – ziaprog
    May 29, 2015 at 13:16
0

Try

$('body').on('click','#myDiv',  function(){ 


});

instead of

 $("#myDiv").click ...

It's the way to access elements dynamically generated.

0
0

You should bind you events in succes function, like:

.success(function (result) {

    $('#breadcrumb').html(result);
     bindEventListener();
})
function bindEventListener(){
  $("#newAddedElement").on('click', function(){
     do somethins...
  })
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.