Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to 'click' a li element

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");
});
like image 498
Zabs Avatar asked Sep 30 '13 09:09

Zabs


People also ask

How to add li dynamically in jQuery?

Answer: Use the jQuery append() Method You can simply use the jQuery append() method to add <li> elements in an existing <ul> element. The following example will add a <li> element at the end of an <ul> on click of the button.

How can get Li tag value in jQuery?

$("#myid li"). click(function() { this.id = 'newId'; // longer method using . attr() $(this). attr('id', 'newId'); });

How to add items in list using jQuery?

Using append() method: The append() method in jQuery is used to add a new element at the end of the selected element. Parameter: This method accepts single parameter element which need to be inserted. Return value: It does not return anything. Example: This example uses append() method to add new element.


1 Answers

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/

like image 62
Edorka Avatar answered Oct 20 '22 04:10

Edorka