user2682527
user2682527

Reputation: 229

how to trigger click event on dynamically created element in jquery

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?

Upvotes: 10

Views: 32101

Answers (4)

bipen
bipen

Reputation: 36551

use event delgation on inside your ready function

try this

 $(function(){
   $('#term').on('click','li:first',function(){
    //do your stuff
   });
 });

Upvotes: -4

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205

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

Upvotes: 13

Dipesh Parmar
Dipesh Parmar

Reputation: 27382

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
});

Upvotes: 8

GautamD31
GautamD31

Reputation: 28773

Try with .trigger() like

 $('#'+liId).trigger('click');

Upvotes: 5

Related Questions