gpt4 book ai didi

javascript - select2 更改事件而不删除已选择的选项

转载 作者:行者123 更新时间:2023-12-03 08:47:23 25 4
gpt4 key购买 nike

我使用带有多个选项的 select2 和编程访问来通过按钮进行选择。它工作正常,但是当我单击按钮时,所有先前选择的值都将被删除,并且仅选择单击按钮中的值。由于我使用的是多重选择,因此添加单击的值并保留先前选择的值而不删除它们是有意义的...除了“更改”之外,是否还有另一个事件可以触发,该事件不会删除值而是添加它们?

<select id="id_entities" class="js-example-programmatic" style="width:100%" multiple="multiple">
</select>

<td><button id="prefix_{{teu.entity_id}}" class="js-programmatic-set-val" value="{{teu.entity_id}}" name="{{teu.entity}}"><i class="fa fa-plus"></i></button></td>
<td>{{teu.entity}}</td>
<td>{{teu.user}}</td>

<script >
$(".js-example-programmatic").select2({
minimumInputLength: 2,
placeholder: "Select entities...",
allowClear: true,
multiple:true,
delay: 250,
tags:false,
ajax: {
url: '/entities/search/autocomplete/',
dataType: 'json',
data: function (parms, page) { return { title: parms.term }; },
},
});
</script>
<script>
var $example = $('#id_entities');
$("button[id^='prefix_']").click(function(){
value = $(this).attr('value');
value_name = $(this).attr('name')
if ($('#id_entities option[value="'+value+'"]').length > 0) {
}
else {
$("#id_entities").append('<option value="'+value+'">'+value_name+'</option>');
}
$example.val(value).trigger("change");
});
</script>

最佳答案

好吧,在没有看到工作演示的情况下,我假设您想要的是将标签附加到 select2 上,而不删除已经存在的标签/多选?如果是这样,您需要评估元素值,并附加新的值,而不仅仅是调用 $example.val(value),它会替换所述元素的值

var data = $(test).select2('data');
data.push({id:5,text:"fixed"});
$(test).select2("data", data, true); // true means that select2 should be refreshed

看起来像是 SELECT2 -> Add data without replacing content 的重复项

关于javascript - select2 更改事件而不删除已选择的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32827605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com