user1857756
user1857756

Reputation: 385

jQuery not working after loading additional content

I am quite new to javascript, but I am using it at my website. Last week I found a script that loads additional content to my page via jQuery. Everything was all right until I noticed that my other scripts stopped working because of that. For example I have a script that binds checkboxes:

<script>
$(document).ready(
    function() {
        $('.class_of_checkbox').click(
            function() {
                if(this.checked == true) {
                    $(".class_of other_checkbox").attr('checked', this.checked);
                }
            }
        );
    }
);
</script>

It is inline code. I have read that it could be caused by function ready(), which fires only when the DOM is loaded, but I am not sure how to solve this problem.

Upvotes: 1

Views: 805

Answers (2)

adeneo
adeneo

Reputation: 318302

Dynamic elements loaded with ajax needs delegated event handlers :

$(document).ready(function() {
    $(document).on('change', '.class_of_checkbox', function() {
        if (this.checked) 
          $(".class_of other_checkbox").prop('checked', this.checked);
    });
});

Replace the second document with the closest non-dynamic parent, use prop() for properties, and use the change event to capture changes in the state of a checkbox.

Upvotes: 2

ShaneA
ShaneA

Reputation: 1365

Use $.ajaxComplete to rebind your actions when the ajax call completes

http://api.jquery.com/ajaxComplete/

$(document).ajaxComplete(function() {
    $('.class_of_checkbox').click(
        function() {
            if(this.checked == true) {
                $(".class_of other_checkbox").attr('checked', this.checked);
            }
        }
    );
});

Upvotes: 1

Related Questions