0

I have a table in a Partial View that is updated when a user selects an option from two different drop downs which are all a part of one form that is submitted and updates the url. Each row in the table contains a check box, and the header contains a "check all" check box so that you can perform bulk delete actions on the rows in the table. Code for my check all check box is written using JQuery on the Index page for the table (Not the partial html file) and is found below:

$('#check-all').on("click", function () {
        var checkAllStatus = this.checked;
        $('.task-checkbox').each(function () {
            this.checked = checkAllStatus;
        });
    });

    $('.task-checkbox').on("click", function () {
        if (this.checked == false) {
            $('#check-all')[0].checked = false;
        }

        if ($('.task-checkbox:checked').length == $('.task-checkbox').length) {
            $('#check-all')[0].checked = true;
        }
    });

On first load of the page, the check all box works exactly as intended. However, if you select an option from one of the drop downs, the partial view is updated and the JQuery above no longer works.

After placing break points and going through lots of different sites and searches, it appears that JQuery is still bound to the old check boxes on the table, and not the new check boxes on the updated partial. Therefore, the check all box no longer works. If you reload the page completely, then the check all box works perfectly. However, I do not want to reload the page when the partial is updated. Hence the use of the partial.

Any ideas? I've tried updating the JQuery on submit of the form that updates the partial, but that triggers before the table is updated and so it still doesn't work. Thanks for any help!

HaydenThrash
  • 67
  • 2
  • 8
  • You need to use a delegated event handler as the event handler you currently use is only bound to the elements that exist when the page loads. See the question I marked as a duplicate for more information – Rory McCrossan Dec 30 '16 at 14:47
  • @RoryMcCrossan found it. I could not find anything about this. Thanks! – HaydenThrash Dec 30 '16 at 14:59
  • the answer in the duplicate question tells you what you need to do. add the event handler to parent element that is not loaded from partial.. like `body` for example.. or `div#content` in a lot of cases.. `$('body').on('click', '#check-all', function() {});` http://api.jquery.com/on/ look at `Direct and delegated events` section – JamieD77 Dec 30 '16 at 15:07

0 Answers0