0

I am trying to display alert when I click the link inside the ul li but somehow it is not working. My jquery fail to select the link which I append it.

MY HTML

<ul id="typeList"></ul>

MY JQUERY

 $("a.type").on("click", function(){                
            alert("click");
 });

$("<li><a href='#' class='type' type =" +results.rows.item(i).Type + " >"+ results.rows.item(i).Type +"</a></li>").appendTo('ul#typeList');

DESIRED LINE CREATED

<ul>
   <li><a class="type" href='#' type ='People'>People</a></li>
   <li><a class="type" href='#' type ='Places'>Places</a></li>
</ul>
shoujo_sm
  • 3,173
  • 4
  • 37
  • 60

3 Answers3

2

Modify your on trigger to catch click events inside ul:

 $("#typeList").on("click", "a.type", function(){                
            alert("click");
 });

This attaches an event handler to only one element (your ul#typeList), but it will only work for a.type elements inside ul.

Zbigniew
  • 27,184
  • 6
  • 59
  • 66
0

You can't attach an event handler to an element that does not yet exists!

Delegate the event to an element that does exist, like in the answer given by @des, or append the element before you attach the handler:

$("<li><a href='#' class='type' type =" +results.rows.item(i).Type + " >"+ results.rows.item(i).Type +"</a></li>").appendTo('ul#typeList');

$("a.type").on("click", function(){                
    alert("click");
});
​

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
-1

Try this for getting the on click

$(function(){
   $(".type").click(function(){                
                alert("click");
     });
});
Akhi
  • 2,242
  • 18
  • 24
  • 1
    This is not correct. The problem is that dynamically elements cannot be selected for the events, because the handlers are attached on load. `.on()` works, but has to be added to a higher level at the DOM. – PeeHaa Aug 19 '12 at 10:47
  • i have edited. now the jquery snippet loads after the page load is complete. – Akhi Aug 19 '12 at 10:51