'Programmatically select a value using the Id retrieved via ajax call
I would like to ask you how to programmatically select a value using the Id retrieved via ajax call. Following the select2 guide I used the following code
$ ('# select2_id'). Val ('1');
$ ('# select2_id'). trigger ('change');
but the field remains empty! I think it's because the options are loaded only when the ajax call starts on the click of select2. Can you suggest me a way to solve?
Te code to initialize the select2 for large options (about 2000 options):
$("#select2_id").select2({
ajax:{
url: '/url/getCompanyType',
type: 'post',
dataType: 'json',
delay: 250,
data: function(params){
return{
_token: CSRF_TOKEN,
search: params.term
}
},
processResults: function(response){
return{
results: response
}
},
cache: true
}
});
Solution 1:[1]
This won't work as the syntax is incorrect:
$ ('# select2_id'). Val ('1');
$ ('# select2_id'). trigger ('change');
This would work:
$('#select2_id').val('1');
$('#select2_id').trigger('change');
The casing of variable names is not arbitrary: it can have an effect on the code.
// this works:
const obj1 = {key1:'val1'}
console.log(obj1.key1)
// and this too:
const obj2 = { key2: 'val2' }
console.log( obj2.key2 )
// but this does not:
const obj3 = { key3: 'val3' }
console.log(obj3.Key3) // see the different casing?
So, returning to your example, the snippet below
- has a
selectthat is not controlled (to show the default behavior) - has a
selectthat is controlled by JS (to show that it works)
$('#select2_id').val('1');
// actually, you don't need the trigger, as the
// .val('newVal') SETS the value of the select
// $('#select2_id').trigger('change');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="not_controlled_id">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<br />
<select id="select2_id">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | muka.gergely |
