Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bootstrap selectpicker and cloning

I have been using bootstrap selectpicker where I've added an Add Button for user to replicate the button as much as he wants. Problem is, selectpicker is not working on the second / cloned element and values of dropdown are just showing and not changing on click.

Main Select:

<div id="main_product">
  <select name="product[]" class="selectpicker" >
   <option value="Tube Lights" >Tube Lights</option>
   <option value="Downlights" >Downlights</option>
  </select>
</div>

Clone Function:

function clone()
{
    var $orginal = $('#main_product');
    var $cloned = $orginal.clone();

    $cloned.appendTo('#new_products');
    // $cloned.find('.bootstrap-select').remove();
    // $cloned.find('select').selectpicker();
}

Note that I tried to reassign the selectpicker to the cloned object which is in comments atm, because it dint work also.

Any help would be really appreciated.

like image 743
user1182071 Avatar asked Aug 10 '16 15:08

user1182071


2 Answers

I came across this problem but if using the latest version now the select is placed inside the .bootstrap-select element for html5 error handling purposes. The remove() also removes the select, a work around is:

Instead of:

$cloned.find('.bootstrap-select').remove();

Use:

$cloned.find('.bootstrap-select').replaceWith(function() { return $('select', this); });

This will replace the .bootstrap-select element with the select element that it contains inside.

like image 183
Michael Ormrod Avatar answered Oct 30 '22 01:10

Michael Ormrod


function clone()    
{    
  //you can use :    
     var $orginal = $('#main_product');    
     var $cloned = $orginal.clone();    
  //Or    
     var $cloned = $('#main_product').clone(); 

  //then use this to solve duplication problem    
     $cloned.find('.bootstrap-select').replaceWith(function() { return $('select', this); })    
     $cloned .find('.selectpicker').selectpicker('render'); 

  //Then Append    
     $cloned.appendTo('#new_products');    
}
like image 35
cm_mehdi Avatar answered Oct 30 '22 01:10

cm_mehdi