简体   繁体   English

select2 - 过滤 ajax 源时无法更改所选选项

[英]select2 - Cannot change selected option when filtering ajax source

I am using the select2 library with in bootstrap 4 modal like this:我在 bootstrap 4 模式中使用 select2 库,如下所示:

<div class="form-group" id="fg-jbInd">
 <label for="jbIndustry" class="control-label">Industry *
  <select type="text" id="jbIndustry" class="form-control" name="jbIndustry">
  </select>
 </label>
</div>

The Javascript looks like this: Javascript 看起来像这样:

$('#jbIndustry').select2({
    placeholder: 'Please select one or more industries or leave blank',

    minimumInputLength : 2,
    dropdownParent: $('#fg-jbInd'),
    ajax: {
    url : '/getindustry',
    dataType : 'json'
    }
});

The ajax call returns data in this format: ajax 调用以这种格式返回数据:

{results : [{id : 1, test: 'option 1'},
            {id : 2, text: 'option 2'}
            ]

Selecting an option and populating the field works.选择一个选项并填充该字段有效。 The problem is when I want to select another option.问题是当我想 select 另一个选项时。 When I start typing I can see option I want but.当我开始输入时,我可以看到我想要的选项但是。 I can select it, but the field is not populated and the original choice is in the field.我可以 select 它,但该字段未填充,原始选择在该字段中。 If I don't limit the database search, I can select another option an populate the field.如果我不限制数据库搜索,我可以 select 另一个选项填充该字段。 I noticed that data needs to contain the original choice or it won't work for me.我注意到数据需要包含原始选择,否则它对我不起作用。

So if the data contains the already selected option like this:因此,如果数据包含已选择的选项,如下所示:

{results : [{id : 1, test: 'option 1'},
            {id : 2, text: 'option 2', selected : true}
            ]

I can select one of the other options.我可以 select 其他选项之一。 If the selected option is not part of the data, it will not work.如果所选选项不是数据的一部分,它将不起作用。 I wonder if anybody had the same issue.我想知道是否有人有同样的问题。 Thanks!!谢谢!!

The issues had to do with how I create the index for each option.这些问题与我如何为每个选项创建索引有关。 For each ajax call I used the array index from the returned mongodb array.对于每个 ajax 调用,我使用返回的 mongodb 数组中的数组索引。 That would create a new index and sometimes a different index for the same item.这将为同一项目创建一个新索引,有时还会创建一个不同的索引。

r.forEach(function(ind, i){
    result.push({'id' : i, 'text' : ind.indName});
});

The solution that worked for me is to use the object id that is created by mongodb.对我有用的解决方案是使用由 mongodb 创建的 object id。 This id is unique and will not change if the same item is returned.此 id 是唯一的,如果返回相同的项目,则不会更改。

r.forEach(function(ind, i){
    result.push({'id' : ind._id, 'text' : ind.indName});
});

Hope this will help somebody!希望这会对某人有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM