在 select2 中预选值

问题描述 投票:0回答:10

Texbox 使用 Select2 动态填充远程调用以及如何设置预选值。这是代码

<input type="hidden" id="e6">

$("#e6").select2({
    placeholder: "Search for a movie",
    minimumInputLength: 1,
    ajax: {
        url: url,
        dataType: 'jsonp',
        data: function (term, page) {
            return {
                q: term, // search term 
                page_limit: 10, }; 
        }, 
        results: function (data, page) { 
                return {results: data};
        }
    }
});    

我尝试预选值 1049

$('#e6').select2('val', '1049');

但这不会设置文本框上的值。

有什么想法吗?

javascript jquery jquery-select2
10个回答
22
投票

如果有人想知道如何解决这个问题

$("#e6").select2('data', {id: '1049', text: 'MyLabel'});

6
投票

对我有用的解决方案(文档中描述的)是:

$('#mySelect2').val('1'); // Select the option with a value of '1'
$('#mySelect2').trigger('change'); // Notify any JS components that the value changed

3
投票

我可以使用它

$("#e6").val("input id of the select2 option here").trigger("change")

3
投票

2019 年这对我有用

    // Create a DOM Option and pre-select by default~
    var newOption = new Option(data.text, data.id, true, true);
    // Append it to the select
    $('#mySelect2').append(newOption).trigger('change');

2
投票

您可以使用 initSelection 方法

initSelection: function(element, callback) {
callback({id: 1, text: 'default selection with id 1' });
},

检查此链接并加载远程数据部分此处


2
投票

用于多项选择...

var li = $("#e6");
li.select2({
    placeholder: "Placeholder"
});

var unselected = li.find('option:not(:selected)');
var selected = [];
for (var i = 0; i < unselected.length; i++) {
    selected[i] = { id: unselected[i].value, text: unselected[i].text };
}
li.select2('data', selected);

1
投票

我知道这是一个老问题,但我也遇到了麻烦。

由于当用户通过 AJAX 输入一些文本时 select2 已被填充,因此它开始为空。因此,之前类型

.val('')
的答案不适用。 例如:

$('#e6').val('1'); // Select the option with a value of '1'
$('#e6').trigger('change'); // Notify any JS components that the value changed

这不起作用,因为没有

.val
可供选择。

然后你需要预加载一些数据到select2。尝试预加载数据的所选答案对我来说有用:

$("#e6").select2('data', {id: '1049', text: 'MyLabel'});

(我猜自从答案被做出并接受以来,插件的代码和行为已经改变)


然后你可以通过两种方式解决这个问题:

  1. 您可以使用文档中的代码强制由 AJAX 预加载

  2. 可以预加载数据并用JS选择。就我而言,我需要这个 select2 预先填充预选元素,同时维护 AJAX 搜索。

我使用了以下内容:

select2 = $('#e6'); 
var option = new Option('MyLabel', 1049, true, true); //The true vars are for preselecting
select2.append(option); //You can repeat this and the previous line for multiselect
select2.trigger('change'); //Call change event so the control updates

用更少的行实现相同的效果:

var option = new Option('MyLabel', 1049, true, true); //The true vars are for preselecting. 1049 is the id.
$('#e6').append(option).trigger('change'); //Append option and call change event 

希望这对某人有帮助。


0
投票

这对我有用

<script>
  $(function() {
    if (window.formPrefill) {
      // setTimeout to force script to run when all the stack on doc.ready is complete.
      setTimeout(() => $(".js-select2-companies").select2('data', window.formPrefill), 10);
    }
  })
</script>

0
投票

根据文档,您可以这样进行多重预选:

$('#mySelect2').val(['1', '2']); 
$('#mySelect2').trigger('change'); // Notify any JS components that the value changed

https://select2.org/programmatic-control/add-select-clear-items


0
投票

就我而言,我选择的值在数据库中以逗号分隔保存,因此我使用了这种方法,它对我有用

        var ele = document.getElementById('farmProduce');
        let val =ele.getAttribute('value')
        for(i=0; i < len; i++){ 
            ele.innerHTML = ele.innerHTML + '<option value="' + farm_produce[i].name + '"' + (val.includes(farm_produce[i].name) ? 'selected="'+true+'"' : null)+'>' + farm_produce[i].name + '</option>';
        }

所以本质上,只需将每个选项的选定属性设置为 true 和 false 就可以解决我的问题

© www.soinside.com 2019 - 2024. All rights reserved.