Search code examples
javascriptjqueryswitchery

Switchery initialize error on AJAX loaded checkbox


I am getting error when initializing checkboxes loaded with Switchery. Note that checkboxes have been loaded using AJAX request

Uncaught TypeError: Cannot read property 'disabled' of undefined at Switchery.isDisabled (switchery.min.js:1) at new Switchery (switchery.min.js:1) at HTMLInputElement. (:3:25) at Function.each (jquery.min.js:2) at n.fn.init.each (jquery.min.js:2) at :1:27

AJAX

$.ajax({
                url: '/admin/item/editReviewAndFinalSettings/{{ $item->id }}',
                type: "POST",
                data: {
                    'type':'{{ucfirst($_GET['type'])}}',
                    'item_group_id':'{{ $item->id }}',
                    'priceType[]':priceType,
                    'optionName[]':optionName,
                    'serviceName[]':serviceName,
                    'itemCodes[]':itemCodes,
                    'partnerCodesStock[]':partnerCodesStock,
                    'itemStockId[]':itemStockId,

                },
                success: function(response) {
                    $(".finalReviewStockContainer").html(response);
                    $(".new-switchery-stock").each(function(k,v) {
                        var elems = document.querySelector('.new-switchery-stock'+k);
                        var switchery = new Switchery(elems[0]);
                    });
                },
                fail: function() {
                    console.log("Error occurred while fetching review and final settings.");
                }
            });

Solution

  • Assigning each input checkbox a unique HTML id attribute before initializing them with Switchery function solved my problem.