1

I'm trying to clone a bootstrap select field, and open the clone immediately.

The code below toggles the original select field.

$('.selectpicker').selectpicker("toggle");

However, when I try to toggle the cloned field, the cloned field is only selected, not opened.

Example here: http://jsfiddle.net/jh4wztab/4/

What can I do to have the cloned bootstrap-select open up immediately after cloning?

HTML

<div id="jurisdictionpicker">
  <select class="selectpicker jurisdiction" data-live-search="true" data-size="8" id="jurisdiction_">
    <option>Philly</option>
    <option>DC</option>
    <option>New York</option>
  </select>
</div>

<BR><BR><BR><BR><BR><BR><BR><BR>

<button id="clonejurisdiction">Clone</button>
<B>Cloned version:</B>
<div class="juris_name">
</div>

Jquery:

$('.selectpicker').selectpicker("toggle");

$(document).on("click", "#clonejurisdiction", function() {
  addselectpicker();
});

function addselectpicker() {
  var clone = $('#jurisdictionpicker').clone();
  clone.find(".selectpicker").attr("id",'jurisdictionpicker2');
  clone.find("[data-id='jurisdiction_']").remove();
  clone.appendTo(".juris_name");
  clone.find('.selectpicker').selectpicker("toggle");
}
isherwood
  • 58,414
  • 16
  • 114
  • 157
user749798
  • 5,210
  • 10
  • 51
  • 85
  • Part of the issue may be the duplicate IDs you're creating. Use incrementing or something else to keep them unique. – isherwood Nov 19 '18 at 21:19
  • Don't think that's it. Even if I change the div ID, it does not work...also, the right clone is being highlighted (so the toggle is at least highlighting the field)...but it's not toggling – user749798 Nov 19 '18 at 21:24

1 Answers1

2

Seems to work if you wrap things in a timeout. Maybe the plugin needs time to do its thing.

$('.selectpicker').selectpicker("toggle");
var index = 1;

$(document).on("click", "#clonejurisdiction", function() {
  addselectpicker();
});

function addselectpicker() {
  var clone = $('#jurisdictionpicker').clone();
  clone.attr('id', 'jurisdictionpicker' + index);
  clone.find(".selectpicker").attr("id", 'jurisdictionpicker' + index);
  index++;
  clone.find("[data-id='jurisdiction_']").remove();
  clone.appendTo(".juris_name");

  setTimeout(function() {
    clone.find('.selectpicker').selectpicker("toggle");
  }, 0);
}

Demo

isherwood
  • 58,414
  • 16
  • 114
  • 157