I have an API sewatanah/getprovinsi
with the GET method and it will return:
[{"id":"0","text":""},{"id":"11","text":"ACEH"},{"id":"12","text":"SUMATERA UTARA"}, ...]
It can be filtered if there is a q
param in that URL based on the substring of text
property.
For example, API sewatanah/getprovinsi?q=ac
will return:
[{"id":"11","text":"ACEH"}, ...]
I implement select2
library like this:
$('.provinsi').select2({
allowClear: true,
placeholder: '-',
minimumInputLength: 3,
ajax: {
dataType: 'json',
url: 'https://ip.jordkris.com/api/sewatanah/getprovinsi',
data: function(params) {
return {
q: params.term
};
},
processResults: function(data) {
return {
results: $.map(data, function(prop) {
return {
id: prop.id,
text: prop.nama
}
})
};
},
cache: true
}
});
$('.provinsi').val('11').trigger('change');
.provinsi {
width: 100%;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<div>
<label>Provinsi</label>
<select class="provinsi"></select>
</div>
The problem is I can’t initialize the value with this:
$('.provinsi').val('11').trigger('change');
I know it can’t be done because data only is retrieved from an Ajax call while .val('11')
didn’t call Ajax. How can I solve this?
3
Answers
I haven't found the solution, but I turn away to use another solution with predefined data from Ajax call, then initialize the value.
You just need to add option tag with selected="selected" attribute.
$('.provinsi').val('11').trigger('change');
It is not necessary.You cannot change the value of a
select
to something that’s not anoption
. You need to make sure that your desiredoption
exists first and then you can set your value. In the modified snippet below I have checked whether theselect
has theoption
you desired and if not, then it’s created before we change the value. I might be misunderstanding the question, please let me know whether this is helpful and what further changes/information you may need.