0
votes

I am calling an URL using Ajax to receive data and populate it inside a select element which is using Select2 and remote data.

The remote data is loading absolutely fine when searching inside the select, but with the below code it doesn't seem to be creating/selecting the option inside the for loop.

The console is showing the correct value returned from the Ajax call but it just doesn't select it in the select element

    $.ajax({
        type: "GET",
        url: "/section/tickets?action=get_update_details&seq=" + $(el).attr("id"),
        cache: false,
        dataType: "json",
        success: function(data) {
            if(data.emails.to !== "") {
                for(var i in data.emails.to) {
                    console.log(data.emails.to[i]);
                    var x = new Option(data.emails.to[i], data.emails.to[i], true, true);
                    $("#contacts_to").append(x).trigger('change');
                }
            }
        }
    });
2
Can u add expected output and actual output? - Taha Metin Bayi
the output is in JSON format, that part is working fine. its the adding and selecting options in the select2 box that isn't working but no errors display in the console for that part either - charlie

2 Answers

0
votes

I tried to simulate what you are trying to achieve, can u point out the troubled part.

$(document).ready(function() {
    $('.js-example-basic-single').select2();
    
    const data = ['Remote Data1', 'Remote Data2'];
    
    for(var i in data) {
        var x = new Option(data[i], data[i], true, true);
        $(".js-example-basic-single").append(x).trigger('change');
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>

<select class="js-example-basic-single" name="state">
  <option value="AL">Alabama</option>
  <option value="WY">Wyoming</option>
</select>
0
votes

It is hard to debug without a complete example. However, your code seems to be working fine.

See this modified version:

  $.ajax({
    type: "GET",
    url: "https://jsonplaceholder.typicode.com/todos/1",
    cache: false,
    dataType: "json",
    success: function(data) {
      console.log(data);
      for (let k in data) {

        var x = new Option(data[k], k, true, true);
        $("#contacts_to").append(x).trigger('change');

      }
    }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-beta.1/js/select2.min.js"></script>
<select name="" id="contacts_to"></select>