7

Can't acces dynamically generated element: This is my function for json request:

$.getJSON('/getJSON.php?selectorcat='+var1, function(jsonData){

var LI_list_html = '';
var sum = 0;

if(jsonData[0])
    {
        $.each(jsonData, function(i,value)
        {
        var catname = jsonData[i].name;
        var id = jsonData[i].id;
        var DIV_html = catname;

        LI_list_html = LI_list_html+'<li class="selectorsub" data-catselectsub="'+id+'" id="SelectorSubcat_'+id+'">'+DIV_html+'</li>';
        });
        }
        else
        {
            LI_list_html = 'No subcats there..';
        }

So when i get the generated html like this:

<ul>
   <li class="selectorsub" data-catselectsub="169" id="SelectorSubcat_169">CAT1</li>
   <li class="selectorsub" data-catselectsub="170" id="SelectorSubcat_170">CAT2</li>
   <li class="selectorsub" data-catselectsub="171" id="SelectorSubcat_171">CAT3</li>
   <li class="selectorsub" data-catselectsub="172" id="SelectorSubcat_172">CAT4</li>
</ul>

I can't acces the li-element trought this:

$("[id^=SelectorSubcat_]").click(function() {
   alert($(this).data('catselectsub'));
});

I think the elemen that is generated isn't ready DOM that's why can't acces them.

Vishwanath
  • 6,284
  • 4
  • 38
  • 57
almirh
  • 151
  • 2
  • 11
  • You are 100% true on the reason why, and this is why we have [delegated events](http://learn.jquery.com/events/event-delegation/). By the way your jquery selector is very complicated, in this case you better use the class from where I see it. – Laurent S. Jan 14 '15 at 14:51
  • 1
    Why not rely on the `.selectorsub` class instead of `[id^=]`? Not only it's more concise it will perform better. – haim770 Jan 14 '15 at 14:54

1 Answers1

14

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call.

As you are creating elements dynamically, You need to use Event Delegation using .on() delegated-events approach.

i.e.

$(document).on('event','selector',callback_function)

Example

$(document).on('click', "[id^=SelectorSubcat_]", function(){
    //Your code
});

In place of document you should use closest static container For better performance.

Satpal
  • 132,252
  • 13
  • 159
  • 168
  • 2
    This is a bad practice to delegate such events to the document. Events should be delegated to the closest static parent for performance reasons. Seeing your reputation you probably know that but I think it should be part of your answer. – Laurent S. Jan 14 '15 at 14:58