carl
carl

Reputation: 4426

Can't change the selection after cloning a select field

I have a select field

<div class="col-xs-10 selectContainer" id="jc_leader_input_field" style="display: inline;">
    <select class="form-control selectpicker" style="margin:0px;padding:0px" value="" data-size="15">
        <option selected="selected" value="0">Option1</option>
        <option value="1">Option0</option>
    </select>
</div>

Now I want to clone this object and include it in my form

var div = document.createElement("div");
var selectfield = $('#jc_leader_input_field').clone();
selectfield.attr('id','test');
selectfield.appendTo(div); 
$('#group_leaders_inputs').append(div);

where #group_leaders_inputs refers to the form. The cloning and insertion works fine, but I can't change any of the options in the copied select field.

I made a fiddle to illustrate the problem... while making it I noticed that without bootstrap-select it actually works fine http://jsbin.com/vonoqazawa/edit?html,output

Upvotes: 3

Views: 1766

Answers (1)

Martin Parenteau
Martin Parenteau

Reputation: 73731

The problem comes from the Bootstrap selectpicker. To make it work, you can:

  1. Remove the selectpicker from the original select control
  2. Clone the original element and add it to the DOM
  3. Reactivate the selectpicker for both select controls

Here is the code:

$(document).ready(function () {
    $(".btn-add").click(function (evt) {
        var $originalDiv = $('#jc_leader_input_field');
        var $originalSelect = $originalDiv.find('.selectpicker');
        $originalSelect.selectpicker('destroy').addClass('tmpSelect');
        var div = document.createElement("div");
        div.className = 'col-xs-12';
        div.style = 'margin:0px;padding:0px';
        var selectfield = $originalDiv.clone();
        selectfield.attr('id', 'test');
        selectfield.appendTo(div);
        $('#group_leaders_inputs').append(div);
        $('.tmpSelect').selectpicker().removeClass('tmpSelect');
    });
});

I saved a modified version of your fiddle here.

Upvotes: 5

Related Questions