Bootstrap toggle doesn't display well when added dynamically

后端 未结 3 1445

I\'m trying to add bootstrap toggle switch dynamically but it does not display well after adding it. Thanks for your help!



        
3条回答
  •  天涯浪人
    2021-01-16 08:04

    I was facing the same issue using bootstrap-toggle. Then after debugging, I understood the behaviour and handled it.

    If the checkbox is not in the dom when page loads, then we need to initialize the toggler when the checkbox is available to the dom and also any listener methods.

    if you are doing an ajax call then in the success method you can add the following in the end.

    $("[data-toggle='toggle']").bootstrapToggle('destroy')                 
    $("[data-toggle='toggle']").bootstrapToggle();
    

    sometimes it may take time to add to the dom and your code gets run before checkbox getting added to the dom, you can wrap the above code in a javascript timer

         setTimeout( () => {
                        $("[data-toggle='toggle']").bootstrapToggle('destroy')                 
                        $("[data-toggle='toggle']").bootstrapToggle();
                        $(".checkbox").change(function() {
                          console.log("toggled");
                           });
                        }, 100 );
    

提交回复
热议问题