Filip Macek
Filip Macek

Reputation: 23

Twitter Bootstrap - selectpicker isn't reacting after adding them by JS

I have a problem with bootstrap add-on select picker. I'm dynamicly adding them by JS, and they won't to be active after adding. They're just there, you can click on them, but you can't select the option. Here is simplified code (or here is LIVE DEMO).

<script>
$(function () {
    $("#add").click(function () {
        $(".pattern").clone().removeClass("hidden pattern").addClass("col-md-24 added").prependTo("#next-line");
    });

    $(".remove").click(function () {
        console.log("remove");
        $(this).parent('.added').remove();
    });
    $('.selectpicker').selectpicker();

    });
</script>
<!-- .... -->
<button type="button" id="add" class="btn btn-success"><span class="fa fa-plus"></span></button>
<form method="POST"> 
        <select class="selectpicker" name="id[]" data-live-search="true">
            <!-- .... -->
        </select>

    <div id="next-line">
    </div>
    <button type="submit" name="save" class="btn btn-lg btn-success"><span class="fa fa-lg fa-send"></span> Send</button>
</form>

<div class="pattern hidden">
    <select class="selectpicker"  name="id[]"  data-live-search="true">
        <!-- .... -->
    </select>
</div>

Thanks for any help.

Upvotes: 2

Views: 198

Answers (1)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

You are cloning an element already that is already an selectpicker instance.

Since your hidden select is only a pattern to clone, I suggest you remove the selectpicker class from it.

Then, you can clone.
But before prepending, give it a unique id that will be usefull to initiate selectpicker on it.

$("#add").click(function() {
    var myClone = $(".pattern").clone().removeClass("hidden pattern").addClass("col-md-24 added");
    var nb = $(".added").length+1;

    myClone.attr("id", "added_"+nb).prependTo("#next-line");
    $("#next-line").find('#added_'+nb).find("select").selectpicker(); //load again
});

That way, your are sure to initiate a selectpicker only on the newly added element.
;)

It is working in this CodePen.

Upvotes: 1

Related Questions