0

EDIT: http://jsfiddle.net/J26Dw/ (click Add)

I want to call, for every checkbox marked with the attribute data-widget="bootstrap-switch", the bootstrapSwitch() plugin. This works fine with this simple function:

$(function () {
    var activator = 'data-widget="bootstrap-switch"';

    $('input[type="checkbox"][' + activator + ']')
        .each(function () {
            $(this).bootstrapSwitch();
        });
});

What if the checkbox was created/added on the fly to the DOM, i.e. clicking a button ?

I tried to catch the DOMNodeInserted event and then call bootstrapSwitch() on the added element, only if the .data('bootstrap-switch') is undefined. I get the following console error (along with a great number of checkboxes :P):

Uncaught RangeError: Maximum call stack size exceeded.

Can anyone point me to the right direction?

$('body').on('DOMNodeInserted', '[' + activator + ']', function(e) {
    var el = $(e.target);

    console.log(el.attr('data-widget')); // Returns "bootstrap-switch", OK

    if (!el.data('bootstrap-switch')) {
        el.bootstrapSwitch(); // Infinite recursion
    }
});
gremo
  • 47,186
  • 75
  • 257
  • 421

1 Answers1

1

bootstrapSwitch has to be causing the recursion loop. It obviously rebuilds the checkbox. In doing so, it must do something to retrigger the DomNodeInserted callback, like remove the target element and re-append it to the document.

In any event, I think this accomplishes what you're trying to do:

$(function () {
    var options   = {},
        selector  = 'input[type="checkbox"][data-widget="bootstrap-switch"]',
        activator = function () { $(this).bootstrapSwitch(options); };

    $(selector).each(activator);

    $('#btn-add').click(function () {
        var $newInput = $('<input>', {
           "type": 'checkbox',
           "data-widget": 'bootstrap-switch'
        });
        $('.holder').append($newInput);
        activator.apply($newInput);
    });

    $('#btn-copy').click(function () {
        var $clonedInput = $('#switch').clone();
        $('.holder').append($clonedInput);
        activator.apply($clonedInput);
    });
});

Fiddle here: http://jsfiddle.net/klenwell/LAUx9/

klenwell
  • 6,978
  • 4
  • 45
  • 84
  • Thank you for your anwser, but the `#btn-add` and `#btn-copy` were just example: checkboxes can be added in other ways to the DOM (i.e. I have no control over it). Is there a solution in this case? – gremo Jul 26 '14 at 08:38
  • @gremo Yes, by applying the same pattern demonstrated here. If there is some reason why that pattern would not work, well, that would have to be articulated, perhaps in a new more carefully worded question. – klenwell Jul 26 '14 at 13:47