Dimitris Damilos
Dimitris Damilos

Reputation: 2438

jQuery element click after AJAX

My project has a page using jQuery UI Tabs. Each tab calls a file using AJAX, each presenting a list. Each <li> element of those lists has a child element like <input type = "checkbox" />.

What I need is for the checkbox element to be checked or unchecked (depending on its previous state) when I click anywhere on the <li>.

I have tried using a function like this <li onclick = "javascript: CheckboxClick();"> and it worked fine, until the user was trying to click on the actual checkbox. Then, the function was running simultaneously with the checkbox's action causing them to cancel each other.

I've tried using a similar version of the function on $(document).ready() in order to exclude the the checkbox child from firing this function, but the lists are created with AJAX and there were not part of the initial DOM. The function did not work. I tried using click instead of on(), since according to w3schools on() method explanation it states "the on() method will work for both current and FUTURE elements (like a new element created by a script)." and I had no success.

The latter try was like this:

$("li.single-line.restore-manager").on("click", function () {
    //code

}).children('input[type="checkbox"]').click(function (e) {

    return false;
});

and actually nothing happens.

Any ideas of how to make this work?

Upvotes: 0

Views: 182

Answers (2)

Manoj Yadav
Manoj Yadav

Reputation: 6612

Updated code to handle checkbox click:

$(document).on("click", 'li.single-line.restore-manager', function(e){ // Use document or parent of li which exists before `AJAX` call
    if (e.target.nodeName != 'INPUT') {
        // your code here
    }
});

Upvotes: 0

DevlshOne
DevlshOne

Reputation: 8457

Is this what you're looking for?

$(document).on("click", "li.single-line.restore-manager", function (e) {
    if (e.target.nodeName != "INPUT") {
        var myChks = $(this).children(":checkbox");
        $.each(myChks, function () {
            if ($(this).is(":checked") === true) {
                $(this).prop("checked", false);
            } else {
                $(this).prop("checked", true);
            }
        });
    };
});

JSFIDDLE

Upvotes: 1

Related Questions