almiros
almiros

Reputation: 151

Can't access dynamically generated element

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.

Upvotes: 7

Views: 9580

Answers (1)

Satpal
Satpal

Reputation: 133453

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.

Upvotes: 14

Related Questions