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,507
  • 1
  • 22
  • 29
Zabs
  • 13,852
  • 45
  • 173
  • 297

6 Answers6

21

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,781
  • 12
  • 24
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
  • 40,216
  • 7
  • 90
  • 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
  • 58,085
  • 24
  • 103
  • 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
  • 22,960
  • 16
  • 44
  • 73
1
$( "li.searchterm" ).on('click',function() {    
   console.log('testing');
});
kasper Taeymans
  • 6,950
  • 5
  • 32
  • 51
1

You can do this without assigning id to ul

$('ul').on('click','li.searchterm',function(){
//do your stuffhere;
});
Mohsin Shoukat
  • 1,190
  • 1
  • 13
  • 22