How to add Chosen Plugin to dynamically created / cloned CSS div?

冷暖自知 提交于 2019-11-27 16:15:35

The work around I came up with was similar to Abhinav's. I removed the Chosen generated code. Stripped the "chzn-done" class from the selectbox. Turned off display:none on the selectbox and then reapplied chose to the selectbox

$j("#masterCats_chzn").remove();
$j("#masterCats").css({display: "inline-block"}).removeClass("chzn-done").addClass("chsn");
$j(".chsn").chosen();

Looking at the chosen source code it seems that you cannot just clone the selects that already has been chosen, as they already have their chzn-done class set, and chosen only applies to the selects that do not have this class set. That means your call to chosen on the new select effectively does nothing.

The select appears as being chosen-enabled because you're cloning the entire group. That is, after call to clone new group already contains a chosen interface, and the select is already hidden. Of course, the chosen interface in the new group is not bound to the new select. Also, clicking on select does not change anything because jQuery.clone does not add new events by default.

Basically, you should never use jQuery.clone to clone complex content (or, more specifically, you should not clone complex content at all). If you want to create a new input group with a new chosen-enabled select, just do it explicitly.

I just stumbled upon here from google. Thought will reply with my .clone() based solution. Here is what I do in my project to use jquery clone and dynamically apply chosen plugin onto it:

html = '';
selectbox = $('#select-box').clone();
selectbox.removeAttr('id').attr({
    'data-placeholder': '(optional)'
}).removeClass('chzn-done').css('display','block');
html += selectbox.wrap('<p>').parent().html();

Works great for me. Removing 'chzn-done' class is mandatory step, otherwise chosen plugin will fail to activate on it.

its true that chosen doesnt work for cloned input. a different approach to get it working is

  clonedInput = $('#fullForm').clone;
    clonedInput.find('div.chzn-container').remove();
    clonedInput.find('selectBoX.withClass').show();
    clonedInput.find('selectBoX.withClass').removeAttr('id');
    clonedInput.find('selectBoX.withClass').removeAttr('data-placeholder');
    clonedInput.find('selectBoX.withClass').removeClass('chzn-done');
    clonedInput.find('selectBoX.withClass').chosen();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!