Ben Bernards
Ben Bernards

Reputation: 187

jQuery - Click() doesn't work when clicking a <li> in an <ul>

Trying to click an item in a dynamically-generated list, but the $.click() function just won't fire.

HTML for the list:

<div>
    <ul id="site_list"> </ul>
</div>

jQuery to generate the list (which works as intended, generating a long list of data with the desired class attribute):

var sites =[];
    $.getJSON("php/ABC.php", function(result){
        $.each(result.Sites, function(i,v){
            sites.push('<li class="site" id="site_'+ ABC + '</li>');
        });

        $('#site_list').append(sites.join(''));
    });

jQuery to be triggered when clicking a list (doesn't work...it doesn't throw errors...just fails to respond. I've tried $('#site') as well, to no avail. I suspect it's due to the method I'm using to generate the <ul>...something is preventing the DOM from properly recognizing each element inside the UL.:

$('li').click(function(){
    $(this).toggleClass("site_selected");
});

Upvotes: 3

Views: 6699

Answers (3)

McFly
McFly

Reputation: 755

The above code looks fine. I just dealt with the same issue and thecodeparadox hit the nail on the head. The input is being loaded dynamically, so it won't work if we put that code in the $(document).ready(function(){...} before it exists.

Just put this code...

    $('li').click(function(){
        $(this).toggleClass("site_selected");
    });

after the list is dynamically generated in the same function (not in doc ready function). If the on-click function is created before the elements are initialized it's a no-go.

There might be an advantage to doing it the other way:

    $('#site_list').on('click', 'li', function(){

However, it's working great for me...

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87073

$('#site_list').on('click', 'li', function(){
    $(this).toggleClass("site_selected");
});

As you're addling li dynamically so you need delegate event handler to li.


Note

Delegate event structure of .on() is like following:

$(container).on(eventName, target, handlerFunction)

Here container point to a Static-element that contains the target element and belongs to DOM at page load.

Upvotes: 11

CambridgeMike
CambridgeMike

Reputation: 4622

Try 'on' instead of 'click'.

$('li').on('click', function(){ $(this).toggleClass('site_selected') } );

Upvotes: 0

Related Questions