14

I have a <ul> element that dynamically generates the <li> elements and simply want to run a onclick event

<ul id="results">
    <li class="device_result searchterm" data-url="apple-iphone-5s">
        <a href="#"> Apple iPhone 5s </a>
    </li>
    <li class="device_result searchterm" data-url="apple-iphone-5c">
        <a href="#"> Apple iPhone 5s </a>
    </li>
</ul>

I've got the following jQuery in a $(document).ready block but it doesn't seem to work - any ideas what I'm doing wrong?

$("li .searchterm").click(function() {  
    console.log("testing");
});
Matheus Avellar
  • 1,479
  • 1
  • 24
  • 29
Zabs
  • 13,252
  • 42
  • 158
  • 277

6 Answers6

20

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/

Edorka
  • 1,731
  • 13
  • 23
14

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

Sachin
  • 39,043
  • 7
  • 86
  • 102
  • 2
    omg.. did i just make that EPIC fail then lol :-) thanks Sachin - much appreciated! – Zabs Sep 30 '13 at 09:59
4

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');
});
Tushar Gupta - curioustushar
  • 56,454
  • 22
  • 99
  • 107
2

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);
}
zzlalani
  • 21,360
  • 16
  • 42
  • 72
1
$( "li.searchterm" ).on('click',function() {    
   console.log('testing');
});
kasper Taeymans
  • 6,750
  • 5
  • 30
  • 50
1

You can do this without assigning id to ul

$('ul').on('click','li.searchterm',function(){
//do your stuffhere;
});
Mohsin Shoukat
  • 1,070
  • 1
  • 12
  • 20