if($('#term').children().length == 0){
$("#term").append("<ul id='ulDynamic' class='ulDynamic'></ul>");
var i;
for(i=1;i<=3;i++){
var liDynamic = "Term "+i;
var liId = "Term"+i;
$("#ulDynamic").append("<li id="+liId+ " class='listDynamic'>"+ liDynamic +"</li>");
if(i==0){
$('#'+liId).click();
}
}
.click() is not working since liId is a dynamically created element. I want the first li element to be auto clicked when the page loads. Is there any other way to do it?
When we want to bind any event to an element, normally we could directly bind to any event of each element using the on() method. Example 1: This example using jQuery on() method to add paragraph element dynamically.
The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
The bind() is an inbuilt method in jQuery which is used to attach one or more event handlers for selected element and this method specifies a function to run when event occurs. event: This is an event type which is passed to the selected elements. data: This is the data which can be shown over the selected elements.
jQuery trigger() MethodThe trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements. This method is similar to the triggerHandler() method, except that triggerHandler() does not trigger the default behavior of the event.
do something like:
$("#term").append("<ul id='ulDynamic' class='ulDynamic'></ul>");
var i;
for(i=1;i<=3;i++){
var liDynamic = "Term "+i;
var liId = "Term"+i;
var $li = $("<li />", {
"id" : liId,
"class" : 'listDynamic'
}).html(liDynamic).click(function() {
alert("clicked:" + this.id);
});
$("#ulDynamic").append($li);
}
$("#ulDynamic").find("li:first").trigger("click");
Demo :: jsFiddle
Try with .trigger()
like
$('#'+liId).trigger('click');
I have seen your ID is starting with Term
so you can use .on() to add click event on DOM that are added later.
Exapmple
$(document).on('click','[id^="Term"]',function(){
//code here
});
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