0

Why I cannot get the text of this newly added multiple child div's. I'm using JQuery to add this dynamic elements. here my sample fiddle: JSFIDDLE

Can someone explain to me where did I go wrong?

Script

var counter = 0;

$("button").click(function() {

$("<div class='child-list-workorder'>\
                            <div class='list-workorder'>\
                               <div class='list-workorder-header'>\
                                 <h3 id='" + counter + "' class='list-workorder-id'>click me " + (++counter) + "</h3>\
                               </div>\
                               <p>" + counter + "</p>\
                            </div>\
                        </div>").appendTo("div.parent-list-workorder");

    });


$("div.list-workorder-header").on("click", "h3.list-workorder-id", function(){
    alert(this.id);
});
Waelhi
  • 175
  • 1
  • 5
  • 19

1 Answers1

1

You have to use delegated event as html is generated dynamically:

$(document).on("click", "h3.list-workorder-id", function(){
    alert(this.id);
});

your div with class child-list-workorder is also generated dynamically so :

$(".child-list-workorder").on("click", "h3.list-workorder-id", function(){
...............

will not work as it is also generated dynamically.

or you can use parent div which has class parent-list-workorder that is loaded on DOM load:

$(".parent-list-workorder").on("click", "h3.list-workorder-id", function(){
    alert(this.id);
});

WORKING UPDATED FIDDLE

Ehsan Sajjad
  • 59,154
  • 14
  • 90
  • 146
  • Thanks mate! it works! but how about I change my `.on SELECTOR` to one of my Class DIV which is `.list-workorder` then I want to alert the value of my `

    `? please see my updated [JSFIDDLE](http://jsfiddle.net/qx1qao6y/7/)

    – Waelhi Oct 17 '14 at 07:33
  • 1
    @Unknownymous2 use ``find()`` see :http://jsfiddle.net/qx1qao6y/8/ – Ehsan Sajjad Oct 17 '14 at 07:41