Problems cloning a checkbox (bootstrap plugin)

Asked

Viewed 117 times

1

http://jsfiddle.net/yusy7zr8/2/

I’m using a bootstrap plugin: http://www.bootstrap-switch.org/

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

if I remove that part:

  • the clone of that checkbox will not work normally.

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

1 answer

1


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

With Bootstrap Switch you no longer only have a checkbox, you have Divs to create the switch effect:

<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>

Thus, 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);
    } 
};

In operation: http://jsfiddle.net/twmh7324/

Another tip: put unique names on the cloned elements. Example: when cloning the line, change its id to line-[Count]. Being Count a counter variable, where you increment every cloning.

  • Note: in the original post I put the wrong link to the fiddle. I edited with the correct link.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.