10
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?

0

4 Answers 4

13

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

Sign up to request clarification or add additional context in comments.

1 Comment

@user2682527 you could mark it as Accepted Answer if it worked for you..!
8

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

1 Comment

He wants to trigger the click event, not bind and event to the the click event.
5

Try with .trigger() like

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

Comments

-4

use event delgation on inside your ready function

try this

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

1 Comment

He wants to trigger the click event, not bind and event to the the click event.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.