How to clone a select element of chosen plugin

℡╲_俬逩灬. 提交于 2019-12-22 09:51:03

问题


I use the Chosen Plugin for jQuery (found here: http://harvesthq.github.com/chosen/ ). It adds extra functionality to select HTML elements.

I wanted to clone a div that contains a select element and increment all the id. The problem is that the clone is ok but the select event apply to the source and not to the clone.

<div id="smallConfig">  
<div id="MainConfig_1">

<select data-placeholder="Choose a country" name="country_1" id="country_1" class="chzn-select">
<option value="" /> 
<option value="Afghanistan">Allemagne</option>
<option value="Afghanistan">Belgique</option> 
</select>

<input style="vertical-align: middle;" type="text" class="large" name="cni" id="f_1" />

<span class="f_help"> </span>
<a  class="add">Add more</a>
</div>
</div>


<script type="text/javascript">

var cur_num = 1;    // Counter used previously.

var addAttendee = function(){
var cloned = $("#MainConfig_" + cur_num).clone(true, true).get(0);
++cur_num;
cloned.id = "MainConfig_" + cur_num;                  // Change the div itself.
$(cloned).find("*").each(function(index, element) {   // And all inner elements.
    if(element.id)
    {
        var matches = element.id.match(/(.+)_\d+/);
        if(matches && matches.length >= 2)            // Captures start at [1].
            element.id = matches[1] + "_" + cur_num;
    }
});
$(cloned).appendTo($("#smallConfig"));
};

$('.add').click(addAttendee); // attach event

</script>

I found this thread How to add Chosen Plugin to dynamically created / cloned CSS div? but i'm not able to adapt to my code.


回答1:


I had the same problem, and solved it like this:

$('.agregar_otro').click(function(e) {

    var num=$(this).attr("id").split("_");
    var cur_num = num[1];    // Counter used previously.
    //...
    var cloned = $("#datos_solicitud_" + cur_num).clone(true, true).get(0);
    ++cur_num;
    cloned.id = "datos_solicitud_" + cur_num;                  // Change the div itself.
    $(cloned).find("*").each(function(index, element) {   // And all inner elements.
        if(element.id)
        {
            var matches = element.id.match(/(.+)_\d+/);
            if(matches && matches.length >= 2)            // Captures start at [1].
                element.id = matches[1] + "_" + cur_num;
        }
    });
    $(cloned).appendTo($("#contenedor"));
    //this lines are the ones that solves the problem
    //id_almacen is the id of the element chosen which was cloned
    $("#id_almacen_"+cur_num).removeClass("chzn-done").css("display", "block").next().remove();
    $("#id_almacen_"+cur_num).chosen();
});


来源:https://stackoverflow.com/questions/14181884/how-to-clone-a-select-element-of-chosen-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!