开发者

How to check/uncheck all checkboxes with Jquery and use .change() function on each checkbox to update database?

开发者 https://www.devze.com 2023-03-07 22:17 出处:网络
I have a form that contains checkboxes.When each c开发者_运维问答heckbox is checked or unchecked, it executes a .change function which calls a .post function.This .post function kicks off a PHP script

I have a form that contains checkboxes. When each c开发者_运维问答heckbox is checked or unchecked, it executes a .change function which calls a .post function. This .post function kicks off a PHP script that updates a database that either sets a status to a 1 (checked) or 0 (unchecked).

This works fine when I am checking or unchecking each checkbox one by one, but when I try to use a check/uncheck-all jquery function which checks or unchecks each of these checkboxes all at once, it seems as though the .change function does not get processed for each changed checkbox and the database is not updated.

Here's the code that "listens" for the .change:

    $('.location_check').change( function () {

        // If the checkbox has been changed to "checked", then run the job to set the db to 1 for that row
        if ($(this).is(':checked')) {
            var $report_f = $(this).attr("name");
            $.post('processes/updateLocationReportFlag.php', { record: $report_f, value: 1 });
        }

        // If the checkbox has been changed to "not checked", then run the job to set the db to 0 for that row
        if ($(this).is(':not(:checked)')) {
            var $report_f = $(this).attr("name");
            $.post('processes/updateLocationReportFlag.php', { record: $report_f, value: 0 });
        }

    });

Here's the code I'm using to check/uncheck all:

    $('#location_checkall').click( function () {

            $(this).parents('#locations_frame').find(':checkbox').attr('checked', this.checked);

    });


Try:

$(this).parents('#locations_frame').find(':checkbox').attr('checked', this.checked).change();

...although, it would probably be wise to add a server-side script to handle multiple checkbox values at once. Many browsers have limits on the number of connections that can be opened at a time and if you have many checkboxes, you may run into this limit, with unexpected and undesirable results.

You may also want to look into JQuery's delegate function to improve performance. It allows you to have a single event handler to which the event is 'delegated' rather than one per DOM element.

0

精彩评论

暂无评论...
验证码 换一张
取 消