Jaydip Vachhani Jaydip Vachhani - 1 month ago 12
jQuery Question

Chosen jquery script is not working

I'm using jQuery chosen in select element to make it more user friendly, but it's not working when i'm doing copy chosen div to another div using jquery



$(document).ready(function() {
$(".chosen").chosen({});

$("#movechosen").click(function() {
var chosenHtml = $(".mycontainer").html();
$(".movecontainer").append(chosenHtml);
});
});

<div class="mycontainer" style="background:#ddd">
Container 1: <select class="chosen" multiple>
<option>Select option</option>
<option>USA</option>
<option>Germany</option>
<option>India</option>
<option>China</option>
<option>Canada</option>
<option>Australia</option>
</select>
</div>
<div class="movecontainer" style="background:#e1e1e1">
Container 2 :
</div>
<input type="button" value="copy to container 2" id="movechosen" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.6.1/chosen.jquery.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.6.1/chosen.css" />





It's getting copy to another container but when you focus on chosen it will not load elements available in it.

Answer

Destroy the plugin when you clone the elements and then reinitialize them after the append:

try the following:

$(document).ready(function() {
  $(".chosen").chosen();

  $("#movechosen").click(function() {
     $(".chosen").chosen("destroy");
    var chosenHtml = $(".mycontainer").html();
    $(".movecontainer").append(chosenHtml);
    $(".chosen").chosen();

  });
});
<div class="mycontainer" style="background:#ddd">
     Container 1: <select class="chosen" multiple>
       <option>Select option</option>
       <option>USA</option>
       <option>Germany</option>
       <option>India</option>
       <option>China</option>
       <option>Canada</option>
       <option>Australia</option>
     </select>
   </div>
  <div class="movecontainer" style="background:#e1e1e1">
     Container 2 : 
  </div>
<input type="button" value="copy to container 2" id="movechosen" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.6.1/chosen.jquery.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.6.1/chosen.css" />