minhur / bootstrap-toggle

Bootstrap Toggle is a highly flexible Bootstrap plugin that converts checkboxes into toggles
http://www.bootstraptoggle.com
MIT License
1.48k stars 440 forks source link

Confirmation Dialogue #234

Open IglooGary opened 1 year ago

IglooGary commented 1 year ago

I believe an on "Click" event is not supported, however is there a way to present a way of displaying some sort of pop up when clicking a toggle element to ask the user if they intend on committing the change. If not the change is reverted (without triggering another on "Change" event and then ending up with an infinite loop.

IglooGary commented 1 year ago

Tried this code, courtesy of "https://stackoverflow.com/questions/46246214/call-function-on-click-on-bootstrap-toggle-checkbox":

var form = $("#Form");

$(document).on('touch.bs.toggle click.bs.toggle', 'div[data-toggle^=toggle]', function (e) {
    var $checkbox = $(this).find('input[type=checkbox]');
    $checkbox.bootstrapToggle('toggle');
    $checkbox.trigger("click");
    e.preventDefault();
})

function isChecked(name) {
        return form.find('[name="' + name + '"]').prop("checked");
    }

$("#Toggle1").on("click", function (event) {
        var name = $(this).attr("name");

        var check = isChecked(name);

        $.confirm({
            title: false,
            content: "Are you sure?",
            buttons: {
                yes: function () {
                    $(this).bootstrapToggle(check ? "on" : "off");
                },
                no: function () {                
                    $(this).bootstrapToggle(check ? "off" : "on");
                }
            }
        });
    });

Works in jQuery-2.2.4, however when debugging in Visual Studio 2022 I can see EVAL scripts being generated per toggle click and the above completely breaks in jQuery 3.6.4.

palcarazm commented 1 year ago

Hi @IglooGary ,

The last lib version is https://github.com/palcarazm/bootstrap5-toggle

Some issues related to unsupported touchevents and double fire of changeEvent had been fixed.

I expect your issue is also fixed 😊

IglooGary commented 1 year ago

Thank you, but sadly due to development restrictions, as in current project scope does not include upgrading NuGet packages at this time I am limited to Bootstrap 3.3.7

IglooGary commented 1 year ago

Think I have fixed it, modified the code as follows:

$(document).on("click.bs.toggle", 'div[data-toggle^=toggle]', function (e) {
        var $checkbox = $(this).find("input[type=checkbox]");

        $checkbox.bootstrapToggle("toggle");

        //$checkbox.trigger("click");
        $checkbox.triggerHandler("click");

        e.preventDefault();
    });