Reputation: 5
I'm having a nightmare of a time trying to get the jQuery Chosen plugin to render correctly after a table row has been cloned. I have scoured and tried many suggestions and 'guaranteed fixes' but can get nothing to work.
Depending on my attempts, I'm either able to get a standard select box to display (or not), or I can manage to show a Chosen select box, which only controls the original row :(
Here is the latest which removes the pre-existing chosen div, and displays a standard select box.
Please note I am able to render all other selects as a Chosen select by simply adding the class required - 'chosen-select', 'chosen-select-no-single' etc, document.ready creates sets chosen() on each object with any chosen-select class
HTML row to be cloned:
<tr id='formListRow' class='row'>
<td><input id='itmDesc0' name='itmDesc0' class='long lockableField' type='text' placeholder='Description' value=''></td>
<td>
<select id='itmCategory0' name='itmCategory0' class='chosen-select-no-single'>
<options></option>
</select>
</td>
</tr>
JS
var $row = document.getElementById("formListRow"); // find row to copy
var $newRow = jQuery($("#formListRow")).clone (true); // copy children too
$newRow.attr('id','newRow' + itm); // change id or other attributes/contents
$newRow.find('select').each(function(){
$(this).removeClass().removeAttr('id').css('display','block').next().remove();
$(this).attr('name','itmCategory' + itm);
$(this).attr('id','itmCategory' + itm);
$(this).addClass('chosen-select-no-single');
$(this).chosen();
});
$("#formListRow").before($newRow);
Guidance is super appreciated. JP
UPDATE
Creating another function for testing purposes so that the Chosen plugin can be applied to the newly cloned element after its been inserted is also not making a lick of difference:
function setNewChosen(itm){
$(".chosen-select-no-single").last().chosen();
}
Upvotes: 0
Views: 2567
Reputation: 557
You need to apply the plugin after you dynamically create elements.
This should work:
$newRow.find('select').each(function(){
$(this).removeClass().removeAttr('id').css('display','block').next().remove();
$(this).attr('name','itmCategory' + itm);
$(this).attr('id','itmCategory' + itm);
$(this).addClass('chosen-select-no-single');
$(this).chosen();
});
Note that the original row should be a native select element and not a chosen element.
Upvotes: 3