I have a
element that dynamically generates the elements and simply want to run a
onclick
event
Either do
$( "li .searchterm" ).on('click', function() {
console.log('testing');
});
OR
<li class="device_result searchterm" data-url="apple-iphone-5s" onclick="clickFunc(1)">
<a href="#">Apple iPhone 5s</a>
</li>
<li class="device_result searchterm" data-url="apple-iphone-5c" onclick="clickFunc(2)">
<a href="#">Apple iPhone 5s</a>
</li>
And the Javascrip
function clickFunc(id) {
console.log('Do something with ' + id);
}
Remove the space in selector
$("li.searchterm").click(function() {
console.log('testing');
});
and You can also use .on
to attach the specific event to the matched elements
$("li.searchterm").on("click",function() {
console.log('testing');
});
Js Fiddle
if you add dinamically put the click on the list but select the items:
$("#results").on("click", ".searchterm", function(event){
console.log('clicked');
});
try on the fiddle: http://jsfiddle.net/emPKS/
Use .on()
As your content is added dynamically so it is not accessible directly ,So you have to use Event delegation.
$('#results').on('click','li.searchterm',function() {
console.log('testing');
});
$( "li.searchterm" ).on('click',function() {
console.log('testing');
});
You can do this without assigning id to ul
$('ul').on('click','li.searchterm',function(){
//do your stuffhere;
});