如何设置 jQuery Select2 的选定值?

157

这段代码属于 Select2 版本 4 之前的代码。

我有一个简单的 select2 代码,它从 AJAX 获取数据。

$("#programid").select2({
  placeholder: "Select a Program",
  allowClear: true,
  minimumInputLength: 3,
  ajax: {
    url: "ajax.php",
    dataType: 'json',
    quietMillis: 200,
    data: function (term, page) {
      return {
        term: term, //search term
        flag: 'selectprogram',
        page: page // page number
      };
    },
    results: function (data) {
      return {results: data};
    }
  },
  dropdownCssClass: "bigdrop",
  escapeMarkup: function (m) { return m; }
});

这段代码是可行的,但是我需要在编辑模式下设置一个值。当用户第一次选择一个值时,它将被保存,当他需要编辑该值时,它必须出现在相同的下拉菜单(select2)中以选择先前选择的值,但我找不到方法。

更新:

HTML代码:

<input type="hidden" name="programid" id="programid" class="width-500 validate[required]">

Select2编程访问在这里无法正常工作。


你应该能够在HTML中设置所选的值,或者使用$("#programid").val() - Explosion Pills
@ExplosionPills 不行,我也试过了,我得到了一个空值。我应该如何使用programid.val()?我从服务器获取了值,然后需要将其设置到select2的隐藏字段中。 - ClearBoth
@ClearBoth 不确定我是否理解你的意思。你是想将Select2组件的"selected"值设置为AJAX检索到的结果之一吗? - An Phan
@AnPhan 是的,有方法可以做到吗? - ClearBoth
@ClearBoth 这里有。请查看我下面的答案。 - An Phan
35个回答

1
在使用AJAX获取数据的Select2控件中,使用.val()将不起作用。因为选项尚不存在,直到控件被打开或用户开始搜索时,AJAX请求才会发出。这进一步复杂化了服务器端的过滤和分页 - 无法保证特定项目何时实际加载到Select2控件中!
因此,处理这个问题的最佳方法是将预选项添加为新选项。对于远程数据,这可能涉及在您的服务器端应用程序中创建新的API端点,以检索单个项目:
$('#mySelect2').select2({
ajax: {
    url: '/api/students'
}
});
var studentSelect = $('#mySelect2');
$.ajax({
    type: 'GET',
    url: '/api/students/s/' + studentId
}).then(function (data) {
// create the option and append to Select2
var option = new Option(data.full_name, data.id, true, true);
studentSelect.append(option).trigger('change');

// manually trigger the `select2:select` event
studentSelect.trigger({
    type: 'select2:select',
    params: {
        data: data
    }
});
});

0

对于多个值,可以这样处理:

$("#HouseIds").select2("val", @Newtonsoft.Json.JsonConvert.SerializeObject(Model.HouseIds));

这将会被翻译成类似于这样的内容

$("#HouseIds").select2("val", [35293,49525]);

0

我做了类似的事情来预设select2 ajax下拉菜单中的元素

      //preset element values
        $(id).val(topics);
       //topics is an array of format [{"id":"","text":""}, .....]
          setTimeout(function(){
           ajaxTopicDropdown(id,
                2,location.origin+"/api for gettings topics/",
                "Pick a topic", true, 5);                      
            },1);
        // ajaxtopicDropdown is dry fucntion to get topics for diffrent element and url

0

你应该使用:

var autocompleteIds= $("#EventId");
autocompleteIds.empty().append('<option value="Id">Text</option>').val("Id").trigger('change');

// For set multi selected values
var data =  [];//Array Ids
var option =  [];//Array options of Ids above
autocompleteIds.empty().append(option).val(data).trigger('change');

// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR) {
    // append the new option
    $("#EventId").append('<option value="' + response.id + '">' + response.text + '</option>');

    // get a list of selected values if any - or create an empty array
    var selectedValues = $("#EventId").val();
    if (selectedValues == null) {
        selectedValues = new Array();
    }
    selectedValues.push(response.id);   // add the newly created option to the list of selected items
    $("#EventId").val(selectedValues).trigger('change');   // have select2 do it's thing
});

0
[jsfiddle_link][1] <select id="lang" multiple >
       <option value="php">php</option>
        <option value="asp">asp</option>
       <option value="java">java</option>
  </select>

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    $("#lang").select2().select2('val',['asp','php']);

<!-- language: lang-html -->


  [1]: https://jsfiddle.net/xrug7f6k/

0

我在Laravel中使用带有ajax源的select2。在我的情况下,它简单地循环选项,我从页面接收并将选项添加到select2中。

$filtri->stato = [1,2,...];

$('#stato')是我的select2,具有服务器端加载功能。

<script>
    @foreach ($filtri->stato as $item)
       $('#stato').append(new Option("{{\App\Models\stato::find($item)->nome}}",{{$item}}, false, true));
    @endforeach
</script>

在我的情况下,我可以使用 find 方法调用选项文本,但也可以通过ajax调用来实现。

0

在@tomloprod的回答基础上进行扩展。如果你碰巧正在使用x-editable,并且有一个select2(v4)字段,并且需要预先选择多个项目。你可以使用以下代码片段:

$("#select2field").on("shown", function(e, editable){
    $(["test1", "test2", "test3", "test4"]).each(function(k, v){
        // Create a DOM Option and pre-select by default~
        var newOption = new Option(v.text, v.id, true, true);
        // Append it to the select
        $(editable.input.$input).append(newOption).trigger('change');
     });
});

并且这是它的实际效果:

var data = [
{
    id: 0,
    text: 'enhancement'
},
{
    id: 1,
    text: 'bug'
},
{
    id: 2,
    text: 'duplicate'
},
{
    id: 3,
    text: 'invalid'
},
{
    id: 4,
    text: 'wontfix'
}
];

$("#select2field").editable({
        type: "select2",
        url: './',
        name: 'select2field',
        savenochange: true,
        send: 'always',
        mode: 'inline',
        source: data,
        value: "bug, wontfix",
        tpl: '<select style="width: 201px;">',
        select2: {
            width: '201px',
            tags: true,
            tokenSeparators: [',', ' '],
            multiple: true,
            data:data
        },
        success: function(response, newValue) {
            console.log("success")
        },
        error: function(response, newValue) {
            if (response.status === 500) {
                return 'Service unavailable. Please try later.';
            } else {
                return response.responseJSON;
            }
        }
    });

var preselect= [
    {
        id: 1,
        text: 'bug'
    },
    {
    id: 4,
    text: 'wontfix'
}
];

 $("#select2field").on("shown", function(e, editable){
    $(preselect).each(function(k, v){
        // Create a DOM Option and pre-select by default~
        var newOption = new Option(v.text, v.id, true, true);
        // Append it to the select
        $(editable.input.$input).append(newOption).trigger('change');
     });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet" />

<link href="//cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap3-editable/css/bootstrap-editable.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap3-editable/js/bootstrap-editable.min.js"></script>

<a id="select2field">bug, wontfix</a>

我猜这个方法即使你没有使用x-editable也可以工作。希望这能帮到某些人。


0

针对那些可能遇到和我一样问题的人,我想补充一点。

我试图设置动态加载选项(来自 AJAX)中所选选项,并根据某些逻辑将其中一个选项设置为所选。

我的问题出在我并没有按照需要匹配值而不是名称来匹配 ID 来设置所选选项!


0
你尝试过将选项的 "selected" 属性设置为 true 吗?

3
如果您需要一个解释性条件回答,以避免给人提出澄清问题的印象,而不是回答问题(对于这种情况应该使用评论而不是答案,请参见 https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead ),那么请按如下方式表述:“如果您的问题是......,那么解决方法是......,因为......。” - Yunnosch

0
select2 < version4 中,有一个选项 initSelection() 用于远程数据加载,通过它可以设置输入框的初始值,就像编辑模式一样。
$("#e6").select2({
    placeholder: "Search for a repository",
    minimumInputLength: 1,
    ajax: { 
        // instead of writing the function to execute the request we use Select2's convenient helper
        url: "https://api.github.com/search/repositories",
        dataType: 'json',
        quietMillis: 250,
        data: function (term, page) {
            return {
                q: term, // search term
            };
        },
        results: function (data, page) {
            // parse the results into the format expected by Select2.
            // since we are using custom formatting functions we do not need to alter the remote JSON data
            return { results: data.items };
        },
        cache: true
    },
    initSelection: function(element, callback) {
        // the input tag has a value attribute preloaded that points to a preselected repository's id
        // this function resolves that id attribute to an object that select2 can render
        // using its formatResult renderer - that way the repository name is shown preselected
        var id = $(element).val();
        if (id !== "") {
            $.ajax("https://api.github.com/repositories/" + id, {
                dataType: "json"
            }).done(function(data) { callback(data); });
        }
    },
    formatResult: repoFormatResult, // omitted for brevity, see the source of this page
    formatSelection: repoFormatSelection,  // omitted for brevity, see the source of this page
    dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
    escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
});

源代码文档: Select2 - 3.5.3


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接