0

My jQuery is a little rusty, hence this noob question:

I have this unordered list,

 <ul data-role="listview" id="list-all-forms">
 </ul>

which I populate from a JSON-object:

function updateChecklists(){
    requestAllForms = $.get("/list-all-forms");

    requestAllForms.promise().done(function(data){
        $.each(data,function(key, val){
            $("<li><a class='checklistObject' id='" + val.id +"'>" + val.name +"</a></li>").appendTo("#list-all-forms");
        });
        $('ul').listview('refresh');
    });
};

However, when I try to get the click event from a link with the class checklistObject in the list, nothing happens...

$(".checklistObject").on("click", function(){
    console.log("click on list object!");

});

How can I get that function to fire?

Jonas Bolin
  • 606
  • 1
  • 11
  • 28

2 Answers2

3

Depending on when you are creating the event handler those object may or may not exist and so the event isn't being attached properly. You could either wait until after they are created to add that event handler or use an event delegate and change your code to be something like:

$('#list-all-forms').on('click', '.checkListObject', function() {
    console.log($(this), "click on list object");
});

Which will work before and after your items are added to the DOM.

Or as mentioned in the comments, something like this: Event binding on dynamically created elements?

Community
  • 1
  • 1
lemieuxster
  • 1,081
  • 7
  • 14
1

Are you sure you're adding the jQuery listener after the elements are there? If not, the selector will just add a click listener to nothing. If you want to load list items later to the list, you can do event delegation.

$("#list-all-forms").on("click", ".checklistObject", function() {
    console.log("click on list object!");
});
Zenorbi
  • 2,504
  • 2
  • 15
  • 18