0

I have a JSON file with a list of elements. For each element in this list a container gets created. This is the code:

$.getJSON('/data/risks.json', function(data) {
var html = '';

$.each(data.risk, function(key, value){
    html += '<div class="elementlist">';
    html += '<br><p><b>'+value.name+'</b><br><br>'+value.description+'</p>';
    html += '</div>';
});
$('#list').html(html);
});

Now I need to know which container was clicked by the user. This:

$('.elementlist').click(function(){
var chosenRisk = $(this).text(); 
    console.log(chosenRisk);
});

works for the container that is already on the page but is for the ones that are created based on the JSON file. What would be the best way to do this?

Greetings

Adam Azad
  • 10,675
  • 5
  • 25
  • 63
ramy
  • 42
  • 13

2 Answers2

2

Delegate the event.

$(document).on('click', '.elementlist', function(){
    var chosenRisk = $(this).text(); 
    console.log(chosenRisk);
});

I would also recommend changing document to '#list' for slightly better performance.

Adam Azad
  • 10,675
  • 5
  • 25
  • 63
1

You need to delegate the handling of the event

$('#list').on( "click", ".elementlist", function(){
    var chosenRisk = $(this).text(); 
    console.log(chosenRisk);
});
Adam Azad
  • 10,675
  • 5
  • 25
  • 63
gurvinder372
  • 61,170
  • 7
  • 61
  • 75