我们有一个表单,我们需要开发动态表格。我们使用select2插件来多选下拉列表。但是当我们添加新行时,select2被禁用,当我们重新初始化时,会发生以下问题。因此,请建议如何解决此问题。
function addTableRow(table){
var $ttc = $(table).find("tbody tr:last");
var $tr = $ttc.clone();
$tr.find("input,select").attr("name", function () { // find name in the cloned row
var parts = this.id.match(/(\D+)_(\d+)__(\D+)$/); // extract parts from id, including index
if (parts) {
return parts[1] + "[" + ++parts[2] + "]." + parts[3]; // build new name
}
}).attr("id", function () { // change id also
var parts = this.id.match(/(\D+)_(\d+)__(\D+)$/); // extract parts
if (parts) {
return parts[1] + "_" + ++parts[2] + "__" + parts[3]; // build new id
}
});
$tr.find("span[data-valmsg-for]").attr("data-valmsg-for", function () { // find validation message
var parts = $(this).attr("data-valmsg-for").match(/(\D+)\[(\d+)]\.(\D+)$/); // extract parts from the referring attribute
if (parts) {
return parts[1] + "[" + ++parts[2] + "]." + parts[3]; // build new value
}
});
//$ttc.find(".new-row").attr("class", "btn btn-danger remove-row").attr("title", "Delete row").unbind("click").click(deleteRow).empty().append("<i class='fa fa-minus'> </i>"); // change buttin function
if (table == "#skills-table") {
$tr.find(".new-row").click(addRow); // add function to the cloned button
}
if (table == "#uniqueIdenifier-table") {
$tr.find(".new-row").click(addUniqueRow); // add function to the cloned button
}
if (table == "#OtherBankList-table") {
$tr.find(".new-row").click(addOtherBankListRow); // add function to the cloned button
}
if (table == "#childorganisation-table") {
$tr.find(".new-row").click(addOtherChildListRow); // add function to the cloned button
}
// reset fields in the new row
$tr.find("select").val("");
$tr.find("input[type=text]").val("");
$tr.find("input[type=hidden]").val("");
// add cloned row as last row
$(table).find("tbody tr:last").after($tr);
// Find the affected form
var $form = $tr.closest("FORM");
// Unbind existing validation
$form.unbind();
$form.data("validator", null);
// Check document for changes
$.validator.unobtrusive.parse(document);
var _select = $tr.find('.select2');
if (_select) {
//console.log(_select);
initializeSelect2(_select);
}
// We could re-validate with changes
// $form.validate($form.data("unobtrusiveValidation").options);
};
function initializeSelect2(selectElementObj) {
//selectElementObj.select2("destroy");
selectElementObj.select2();
}