Disciples Disciples - 22 days ago 7
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
clone()
method.

Related jsfiddle:
https://jsfiddle.net/qeodcg3o/

Joe Joe
Answer

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>
  </select>
</li>

<li id='ws_add_country' style="text-align: center;">
  <script>
    var i = 0;
  $(document).ready(function(){
    addCountry();
  })
    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);
      clone.show();
      clone.insertAfter('#ws_add_country').wrap('<li></li>').select2();
    }
  </script>

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

</li>