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.
To attach event handlers to the dynamically created button, we need to select the button with a class of btn and add an event listener of click . We're saying that onclick of the button, the p tag with a class of moreInfo should display block .
onclick = function () { alert("hi jaavscript"); };
You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event. Save this answer.
If you try to bind the elements that are dynamically added to the DOM using the click() method of jQuery, this will not work, because it only binds the click event to elements that exist at the time of the “binding”. To bind the click event to all existing and future elements, use jQuery's on() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With