0

I am trying to create a table, made with buttons, that allow me to get into a Geological Time Chart. I create 4 buttons with class "levels" and then I execute a function that return the childs from an API.

The point is that the function works the first time, but then it stop working for the new created buttons. Here is my code:

$(".levels").click(function clickLevel(){

var buttonName = $(this).text();
console.log($(this).text());


$.each(JsonObject, function(index,value){

    if (buttonName == value.nam){
        lvloid = value.oid;
        console.log(lvloid);                        
    }   

    if(lvloid == value.pid){
        console.log(lvloid == value.pid);
        var button = "<button class=\"btn-flat levels\" style=\"background-color:"+value.col+";\">"+value.nam+"</button>";
        $(".conti").append(button);

    }

});

});

I guess the problem is that I am creating the class within the function, but I don't find any other solution (I tried to declare the function and then call it in the .click event, but this don't even work!).

Thank you to all of you!!

cecimo
  • 25
  • 7
  • This post can help you solve this issue: http://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements – Ricardo Pontual Jul 19 '16 at 11:35

2 Answers2

1

Instead of :

$(".levels").click()

Use

$(document).on('click', '.levels', function(){
});

The reason behind this is, $(".levels").click() searches in the static dom, and you are generating the button dynamically. For dynamic content $(document).on() is used.

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
-1

Use

$(".levels").on('click', function(){
});

instead of

$(".levels").click(function clickLevel(){

});
nikhil mehta
  • 972
  • 15
  • 30
  • 1
    just using "on" by itself doesn't help. You have to delegate the event from a pre-existing element. – ADyson Jul 19 '16 at 11:38
  • @ADyson no need as per the jquery documentation http://api.jquery.com/delegate/ it says As of jQuery 1.7, .delegate() has been superseded by the .on() method – nikhil mehta Jul 19 '16 at 11:47
  • yes, that's true, but I'm not talking about the function called delegate. I'm talking about the process of delegating events from a static element to a dynamically created one. Read the section called "Direct and delegated events" at http://api.jquery.com/on/ . Your version doesn't work because the elements with the class "levels" that the OP is targeting don't exist at page load, which is when your event is bound. You have to bind to an element which exists at that point, and then give .on() instructions on what to delegate it to. As per the accepted answer, in fact. – ADyson Jul 19 '16 at 11:49
  • Thank you very much also to you @nikhilmehta! – cecimo Jul 19 '16 at 11:55