1

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/select2@4.0.6-rc.0/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/select2@4.0.6-rc.0/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?

Jordy
  • 1,802
  • 2
  • 6
  • 25
  • Which version of select2 are you using? – Benilson May 08 '23 at 11:33
  • @Benilson `select2` version 4. – Jordy May 08 '23 at 11:48
  • @Benilson specifically `select2 v4.0.6-rc.0`. – Jordy May 08 '23 at 12:05
  • Hi, if you know what you need to keep selected you can add option tag in your select-tag with that option selected and when searching happens it will change automatically . – Swati May 08 '23 at 12:48
  • Hi @Swati, thanks for your advice. Can you give me an example for that? – Jordy May 08 '23 at 12:52
  • 1
    You can check [this](https://stackoverflow.com/questions/30316586/how-can-i-set-the-initial-value-of-select2-when-using-ajax) post for same. – Swati May 08 '23 at 15:27
  • Can you create a minimal reproducible example of this problem and steps of reproduction so we can play around with it? – Lajos Arpad May 10 '23 at 13:05
  • @LajosArpad Sure, you can try [this API](https://ip.jordkris.com/api/sewatanah/getprovinsi?q=ac). – Jordy May 11 '23 at 11:43
  • Thanks, Jordy, but I would be interested to see an editable reproducible example, a jsfiddle or the like. It is probably not very difficult for you to make such an example, but such an example would significantly raise my confidence that I tackle the exact problem you have. – Lajos Arpad May 11 '23 at 12:01
  • @LajosArpad Yes, I have added the working fiddle in the updated question above. – Jordy May 11 '23 at 12:06

3 Answers3

1

You just need to add option tag with selected="selected" attribute.

  <select class="provinsi">
    <option value="31" selected="selected">DKI JAKARTA</option>
  </select>

$('.provinsi').val('11').trigger('change'); It is not necessary.

$('.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/select2@4.0.6-rc.0/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/select2@4.0.6-rc.0/dist/js/select2.min.js"></script>

<div>
  <label>Provinsi</label>
  <select class="provinsi">
    <option value="31" selected="selected">DKI JAKARTA</option>
  </select>
</div>
Benilson
  • 564
  • 2
  • 7
0

I haven't found the solution, but I turn away to use another solution with predefined data from Ajax call, then initialize the value.

$.ajax({
  url: 'https://ip.jordkris.com/api/sewatanah/getprovinsi',
  success: (res) => {
    $('.provinsi').append($.map(res, (obj) => {
      return $('<option>').val(obj.id).text(obj.nama);
    }));
    $('.provinsi').select2();
    $('.provinsi').val('31').trigger('change');
  },
  error: (err) => {
    console.error(err);
  }
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.0.6-rc.0/dist/css/select2.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.6-rc.0/dist/js/select2.min.js"></script>

<div>
  <label>Provinsi</label>
  <select class="provinsi"></select>
</div>
Jordy
  • 1,802
  • 2
  • 6
  • 25
0

You cannot change the value of a select to something that's not an option. You need to make sure that your desired option exists first and then you can set your value. In the modified snippet below I have checked whether the select has the option 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.

$('.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
  }
});

let v = {key: 11, text: 'ACEH'};
let provinsi = $('.provinsi');
if (!provinsi.find(`option[value=${v.key}]`).length) {
    provinsi.append(`<option value=${v.key}>${v.text}</option>`)
    provinsi.val('11').trigger('change');
}
.provinsi {
  width: 100%;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.0.6-rc.0/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/select2@4.0.6-rc.0/dist/js/select2.min.js"></script>

<div>
  <label>Provinsi</label>
  <select class="provinsi">
  </select>
</div>
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175