【问题标题】:Issue with duplicating select2 selects with jQuery使用 jQuery 复制 select2 选择的问题
【发布时间】:2019-01-17 23:08:46
【问题描述】:

我正在做一个项目,我们需要创建一个可扩展的表单,因此用户可以通过单击“添加新项目”按钮输入任意数量的项目,该按钮将克隆一行并允许他们选择新选项以添加到表单中。

到目前为止,我们有一行元素,如下所示:

<div class="input-group">
  <select class="form-control name-select" name="name">
    <option value disabled selected>Component Name</option>
  </select>
  <select class="form-control type-select" name="sale_type">
    <option value disabled selected>Sale Type</option>
    <option value="1">type 1</option>
    <option value="2">type 2</option>
  </select>
  <input type="input" class="form-control" placeholder="number">
  <input type="text" class="form-control" placeholder="Total number" readonly>
  <input type="text" class="form-control" placeholder="Cost per item" readonly>
  <input type="text" class="form-control" placeholder="Total cost" readonly>
</div>

我们目前只是在前端工作,但这些选择将有很多选项。

我的问题是我们需要能够复制这一行并且仍然能够使用 select2 框。 通过查看它,我们意识到我们需要销毁 select2,克隆它,然后重新初始化它。这不是问题,但由于某种原因,当我们复制该行项目时,除了最近创建的一个框外,所有 select2 框都只是正常的选择。就好像它只允许每个 select2 中的一个,这是不理想的,因为我们需要所有这些都工作以允许从一长串选项中轻松选择。

我们用来复制项目的代码是:

var base = element.find('.item-row.base').first();

base.find('.name-select').select2('destroy');
base.find('.type-select').select2('destroy');

var itemRowClone = base.clone();

itemRowClone.removeClass('base')

itemRowClone.find('select').each(function(){
    $(this).attr('name', $(this).attr('name') + element.find('.item-row').length)
});

element.find('.new-items').append(itemRowClone);

base.find('.name-select').select2();
base.find('.type-select').select2();

itemRowClone.find('.name-select').select2();
itemRowClone.find('.type-select').select2();

console.log('reinitialised')

就像我说的,它很好地破坏了 select2,但是当它重新初始化它们时,它只允许每个选择的一个实例成为 select2,其余的都是默认选择。

如果有人有任何想法,那就太棒了!

提前致谢

【问题讨论】:

    标签: jquery clone jquery-select2


    【解决方案1】:

    最后,我通过照原样复制 select2 标签来使用它,而不破坏它。然后手动删除由 select2 生成的跨度标签,该标签直接位于选择标签之后。然后我删除了类select2-hidden-accessible,以及属性data-select2-id,然后在select标签上调用了select2()方法。

    itemRowClone.find('span.select2').remove();
    itemRowClone.find('select').removeClass('select2-hidden-accessible');
    itemRowClone.find('select').removeAttr('data-select2-id');
    
    arrangement.find('.new-items').append(itemRowClone);
    
    itemRowClone.find('.name-select').select2();
    itemRowClone.find('.type-select').select2();
    

    希望这可以帮助遇到这种情况的其他人!

    【讨论】:

    • 在我看来这可以通过 $cloneSelect2.select2("destroy");
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 2017-05-13
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 2010-10-16
    相关资源
    最近更新 更多