Disciples Disciples - 1 year ago 170
Javascript Question

How to clone select2 with selected option?

so I wonder how to properly clone select2 with jquery? Problem is when I use clone, it makes my clone's

width 1px
and it doesn't copy selected value. I tries multiple ways, cloning with true-arguments, cloning with events, but nothing so far.

I think problem is somehow related to

Related jsfiddle:

Joe Joe
Answer Source

This works:

<li style="display:none">
  <select id="ws_language_template" name="language">
    <option value="1">English</option>
    <option value="2">Abkhazian</option>
    <option value="3">Afar</option>
    <option value="4">Afrikaans</option>
    <option value="5">Akan</option>
    <option value="6">Albanian</option>
    <option value="7">Amharic</option>
    <option value="8">Arabic</option>

<li id='ws_add_country' style="text-align: center;">
    var i = 0;
    function addCountry(){
      var sel = $('#ws_language_template');//.insertAfter('#ws_add_country').wrap('<li class="yes"></li>').select2().css('width','20%');
      var clone = sel.clone(true, true);
      i ++;
      clone.attr("id", "ws_language"+i);

  <span onclick='addCountry()' id="add_country" style="cursor: pointer;color: #21277c;border: 2px;border-bottom: dashed 1px #21277C;" >
    Add another country

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download