-1

I can generate a list of accordions after an AJAX call in this way:

data.items.forEach(function(item,index) {
                if(item.desciption != "") {
                    $('#accordionList').append(
                        templateAccordion(item, index)
                );
          }
});

where templateAccordion is:

var templateAccordion = function(item, index) {
        return '<div class="card">' +
        '<div class="card-header" id="heading_'+index+'" data-toggle="collapse" onclick="test('+index+')" data-target="#collapse_'+index+'" aria-expanded="false" aria-controls="collapse_'+index+'">' +
        '<h5 class="mb-0">'+
          '<button class="btn btn-link collapsed">'+
            item.desciption + 
          '</button>'+
        '</h5>'+
      '</div>'+ 
      '<div id="collapse_'+index+'" class="collapse" aria-labelledby="heading_'+index+'" data-parent="#accordionList">'+
        '<div class="card-body">' +

        '</div>'+
      '</div>'+
    '</div>'
    }

Problem:

I need to call another service when I click over the header of each accordion to get other data about that element. To do this, I thought 2 possible ways.

The first one is the onclick="" function on the header of the element (like in my example). But this solution doesn't work because I get a Uncaught ReferenceError: test is not defined (and the function exists in my javascript).

The second is trigger the click function using the id of the header. But it's dynamic as you can see. So I don't have it because it could be 1,2,3 and so on.

I can't loop over the whole list and try to get the correct id. It is unthinkable.

Is there any onther way? Maybe just understand why it gets me Uncaught ReferenceError: test is not defined?

CodeBoyCode
  • 1,993
  • 9
  • 26
Atlas91
  • 5,238
  • 14
  • 53
  • 117

1 Answers1

3

This should work:

$('#accordionList').on('click','.card-header', function(){
    var id = $(this).attr('id');
});
Andy
  • 2,482
  • 1
  • 21
  • 31