skip to Main Content

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


  1. Chosen as BEST ANSWER

    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://corsproxy.io/?https://jordy.s-ul.eu/jQ1rr3D5',
      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/[email protected]/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/[email protected]/dist/js/select2.min.js"></script>
    
    <div>
      <label>Provinsi</label>
      <select class="provinsi"></select>
    </div>


  2. 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/[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">
        <option value="31" selected="selected">DKI JAKARTA</option>
      </select>
    </div>
    Login or Signup to reply.
  3. 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 = 11;
    let provinsi = $('.provinsi');
    if (!provinsi.find(`option[value=${v}]`).length) {
        provinsi.append(`<option value=${v}>${v}</option>`)
        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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search