Problems cloning a checkbox (bootstrap plugin)

1

link

I'm using a bootstrap plugin: link

I'm trying to clone this checkbox , but the checkbox is not being checked (for on and off ) after being cloned.

If I remove this part:

  • The clone of this checkbox will not function normally.

    $("[name='chk-teste']").bootstrapSwitch();
    
  • If I remove this plugin, it works (with regular comboboxes)

asked by anonymous 04.08.2015 / 01:57

1 answer

1

When you use Bootstrap components and others that transform HTML inputs, they modify your DOM by adding several other elements.

With the Bootstrap Switch you no longer have just one checkbox, you have divs to create the effect of the switch:

<div class="bootstrap-switch bootstrap-switch-wrapper bootstrap-switch-animate bootstrap-switch-off" style="width: 102px;">
    <div class="bootstrap-switch-container" style="width: 150px; margin-left: -50px;">
        <span class="bootstrap-switch-handle-on bootstrap-switch-primary" style="width: 50px;">ON</span>
        <span class="bootstrap-switch-label" style="width: 50px;">&nbsp;</span>
        <span class="bootstrap-switch-handle-off bootstrap-switch-default" style="width: 50px;">OFF</span>
        <input type="checkbox" name="chk-teste">
    </div>
</div>

So, you should remove all the divs, add a new checkbox, and activate it as a Bootstrap Switch. I added some snippets to your existing code:

var ativador = function () { $(this).bootstrapSwitch({}); };

var acao = function() {
    var campo = this;

    if (campo.value == "+") {
        var tr = campo.parentNode.parentNode;
        var novoTr = tr.cloneNode(true);
        var botoesNovos = novoTr.getElementsByClassName('btn-add');

        // Remove o DIV do checkbox bootstrap (pode dar blink na tela)
        $(novoTr).find('div').remove();        

        // Adiciona um checkbox "puro"
        var $novoCheck = $('<input>', {
           "type": 'checkbox',
           "data-widget": 'bootstrap-switch'
        });
        $('td:first', $(novoTr)).append($novoCheck);
        // Transforma o checkbox em bootstrap-switch
        ativador.apply($novoCheck);

        for(var i=0;i<botoesNovos.length;i++){          
            botoesNovos[i].addEventListener('click', acao, false);
        }

        tr.parentNode.insertBefore(novoTr, tr.nextSibling);
    } 
};

Running: link

Another tip: place unique names on cloned elements. Example: When cloning the line, change its id to line- [count]. Being count a counting variable, where you increment each clone.

    
04.08.2015 / 03:14