Problem using .clone () and select

3

I am passing elements from one section to another, the big problem I have, is that when cloning it does not save the option selected, simple example to understand me:

<div id="content">
  <div class="copy">
    <select>
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
    </select>
  </div>
</div>
<button type="button" id="clone">Clonar</button>
<div id="container">

</div>



 $('#clone').on('click', function() {
     $('#content .copy').clone().appendTo('#container')
 }

It clones it perfectly, but still does not keep the information that was selected. Someone knows what is going on or what other method they recommend me to use.

    
asked by DoubleM 29.11.2018 в 03:47
source

1 answer

3

jQuery has a limitation on the clone function. The relevant part translated:

  

Note: For performance reasons, the dynamic state of certain form elements (eg: data entered by the user in textarea and selections made in select ) is not copied to the cloned elements. [...]

But you can return to assign the value to the new element after it has been added to the page:

$('#clone').on('click', function() {
  var original = $('#content .copy');
  var valor = original.find('select').val();
  var clon = original.clone().appendTo('#container');
  clon.find('select').val(valor);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">
  <div class="copy">
    <select>
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
    </select>
  </div>
</div>

<button type="button" id="clone">Clonar</button>

<div id="container">
</div>
    
answered by 29.11.2018 в 04:11