user889030 user889030 - 5 months ago 18
jQuery Question

JQuery Change function not work with ajax content

my html code

<div class="gridRowsContainer">
<div ng-repeat="item in ActiveUserData.ListModel track by $index" class="">
<!-- Checkboxes Generated/inserted here by ajax -->
<div class="gridRow pnl-no-dimiss" ng-style="getRowCss(item)" id="user_list_07c4ab10-4ad0-44d1-9d65-aeee70be20a6" style="background-color: transparent;">
<div>
<div class="userLight listViewRow">
<div class="ms-ChoiceField f-choice" data-hint="Users" data-value="SelectItem">
<input id="selectUser_07c4ab10-4ad0-44d1-9d65-aeee70be20a6" class="ms-ChoiceField-input dataListField ng-valid ng-dirty ng-valid-parse ng-touched" type="checkbox" ng-model="item.isChecked" ng-change="UpdatedSelectedUsers(item)" tabindex="0" aria-checked="false" aria-invalid="false">
</div>
</div>
</div>
</div></div></div>


My jQuery Code

$(":checkbox").change(function() {
$(this).closest('[ng-repeat*="item"]').nextAll('[ng-repeat*="item"]:lt(3)').find('[type="checkbox"]').prop('checked', this.checked);
});


so it not working when content is loaded via ajax , any idea how to make it working when content is loaded via ajax on page load and also more checkboxes entries are loaded when user scroll down .

working jsfiddle with static checkboxes list :: https://jsfiddle.net/mmzth076/7/
but not work with ajax

Answer

Try adding the change function in the success handler of the ajax:

$.ajax {
  method: 'GET',
  success: function() {
    load_grid(); //Code that builds the grid with the checkboxes
    $(":checkbox").change(function() {
      $(this).closest('[ng-repeat*="item"]')
        .nextAll('[ng-repeat*="item"]:lt(3)')
        .find('[type="checkbox"]')
        .prop('checked', this.checked);
    });
  }
}

You can also use any known parent of the grid that is available in the DOM at the time of binding the click event handler.

$('body').on('change', ":checkbox", function () {
    $(this).closest('[ng-repeat*="item"]')
        .nextAll('[ng-repeat*="item"]:lt(3)')
        .find('[type="checkbox"]')
        .prop('checked', this.checked);
});

Replace body with any known predecessor at the time of binding.

Comments