简体   繁体   中英

select2 - Cannot change selected option when filtering ajax source

I am using the select2 library with in bootstrap 4 modal like this:

<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:

$('#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:

{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. 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. If I don't limit the database search, I can select another option an populate the field. 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. 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. 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. This id is unique and will not change if the same item is returned.

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

Hope this will help somebody!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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