2

I am creating multiple <p></p> elements dynamically in jquery.

var output = '<p>' + results.length + ' matches found</p>';
$.each(results, function (index, result) {
        output += '<p class="'+result.text+'">- ' + result.text + '</p>';
 });
$('#search-output').html(output);

Now when i click on the <p> elements i want the text value. I tried like

 $('#search-output').click(function(e){
        var data= $(this).text();
        console.log(data);
        $("#output").text(data);
    })

But then all the contents of #search-output is showing. I want to get the value of the <p> I clicked. any help

Katstevens
  • 1,556
  • 13
  • 29
Subho
  • 921
  • 5
  • 25
  • 48
  • 1
    Possible Duplicate http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – John R Jun 20 '16 at 06:23

2 Answers2

6

Read about Event delegation

$('#search-output').on('click', 'p', function(e){
    var data= $(this).text();
    console.log(data);
    $("#output").text(data);
});
Rayon
  • 36,219
  • 4
  • 49
  • 76
0

For dynamically create elements you need to edit jquery code and fire click event on body something like this

 $('body').on('click','#search-output p',function(e){
    var data= $(this).text();
    console.log(data);
    $("#output").text(data);
})
webdevanuj
  • 675
  • 12
  • 22