[jquery] Setting initial values on load with Select2 with Ajax

I have select2 controls set up with Ajax (have both single and multiple). I'm trying to have some values on page load but I'm not able to get this to work however. My code for select2 is given below:

function AjaxCombo(element, url, multival ){  // multival = true or false
  multival = multival || false;
  $(element).select2({
   minimumInputLength: 2,
   multiple: multival,
   separator: '|',
   ajax: {
     url: url,
     dataType: 'json',
     data: function (term, page) {
        var targetname = $(this).attr('name');
        var target = targetname.slice(targetname.indexOf("[")+1, targetname.indexOf("]"));
       return {
         targettype: "search",
         target: target,
         search: term
       };
     },
     results: function (data, page) {
       return { results: data };
     }
   }
 });
}
AjaxCombo(".ajaxselect", "includes/linkedcontrol.php", false);
AjaxCombo(".ajaxmultiselect", "includes/linkedcontrol.php", true);

The Ajax combo works fine, am having trouble only with the initial values load. I tried this code below but couldn't get it to work:

initSelection : function (element, callback) {
    var elementText = $(element).attr('data-initvalue');
    callback(elementText);
}

My HTML from php is returned as below :

<input name='header[country]' class='ajaxselect'  data-initvalue='[{"id":"IN","name":"India"}]' data-placeholder='Select Country' value='' />

I see that values are populated from php, only my jquery is having issues. My values in the control show up as US | United States of America. I guess I have edited the select2 source for getting this format as default without using format option.

Can anyone please help me populate the default values? Thanks in advance.

EDIT: This question pertains to Select2 version <4.0. This option is removed from v4.0 and is much simpler now.

This question is related to jquery ajax jquery-select2

The answer is


Maybe this work for you!! This works for me...

initSelection: function (element, callback) {

            callback({ id: 1, text: 'Text' });
}

Check very well that code is correctly spelled, my issue was in the initSelection, I had initselection


In my case the problem was rendering the output.. So I used the default text if the ajax data is not present yet.

  templateSelection: function(data) {
    return data.name || data.element.innerText;
  }

Ravi, for 4.0.1-rc.1:

  1. Add all <option> elements inside <select>.
  2. call $element.val(yourarray).trigger("change"); after select2 init function.

HTML:

<select name="Tags" id="Tags" class="form-control input-lg select2" multiple="multiple">
       <option value="1">tag 1</option>
       <option value="2">tag 2</option>
       <option value="3">tag 3</option>
 </select>

JS:

var $tagsControl = $("#Tags").select2({
        ajax: {
            url: '/Tags/Search',
            dataType: 'json',
            delay: 250,
            results: function (data) {
                return {
                    results: $.map(data, function (item) {
                        return {
                            text: item.text,
                            id: item.id
                        }
                    })
                };
            },
            cache: false
        },
        minimumInputLength: 2,
        maximumSelectionLength: 6
    });

    var data = [];
    var tags = $("#Tags option").each(function () {
        data.push($(this).val());
    });
    $tagsControl.val(data).trigger("change");

This issue was reported but it still opened. https://github.com/select2/select2/issues/3116#issuecomment-146568753


Late :( but I think this will solve your problem.

 $("#controlId").val(SampleData [0].id).trigger("change");

After the data binding

 $("#controlId").select2({
        placeholder:"Select somthing",
        data: SampleData // data from ajax controll
    });
    $("#controlId").val(SampleData[0].id).trigger("change");

Updated to new version:

Try this solution from here http://jsfiddle.net/EE9RG/430/

$('#sel2').select2({
multiple:true,
ajax:{}}).select2({"data": 
     [{"id":"2127","text":"Henry Ford"},{"id":"2199","text":"Tom Phillips"}]});

I`ve added

initSelection: function (element, callback) {

      callback({ id: 1, text: 'Text' });
}

BUT also

.select2('val', []);

at the end.

This solved my issue.


Change the value after the page loads

$('#data').val('').change();


var elem = $("#container").find("[name=elemMutliOption]");
for (var i = 0; i < arrDynamicList.length; i++)
{
   elem.find("option[value=" + arrDynamicList[i] + "]").attr("selected", "selected");
}
elem.select2().trigger("change");

This will work for people who are using the same view for multiple section in the page, with that being said it will work the same way for auto-setting defaults in your page OR better a EDIT page.

The "FOR" goes through the array that has existing options already loaded in the DOM.


A very weird way for passing data. I prefer to get a JSON string/object from server and then assign values and stuff.

Anyway, when you do this var elementText = $(element).attr('data-initvalue'); you're getting this [{"id":"IN","name":"India"}]. That result you must PARSE it as suggested above so you can get the real vales for id ("IN") and name("India"). Now there are two scenarios, multi-select & single-value Select2.

Single Values:

$(element).select2({
    initSelection : function (element, callback) {
        var data = {id: "IN", text: "INDIA"};
        callback(data);
    }//Then the rest of your configurations (e.g.: ajax, allowClear, etc.)
});

Multi-Select

$("#tags").select2({
    initSelection : function (element, callback) {
        var countryId = "IN"; //Your values that somehow you parsed them
        var countryText = "INDIA";

        var data = [];//Array

        data.push({id: countryId, text: countryText});//Push values to data array


        callback(data); //Fill'em
    }
});

NOW HERE'S THE TRICK! Like belov91 suggested, you MUST put this...

$(element).select2("val", []);

Even if it's a single or multi-valued Select2. On the other hand remember that you can't assign the Select2 ajax function to a <select> tag, it must be an <input>.

Hope that helped you (or someone).

Bye.


These answer are pretty outdated. Some work in certain situations, but this is in the documentation. https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2

Basically you need create and append the selected options.

// Set up the Select2 control
$('#mySelect2').select2({
    ajax: {
        url: '/api/students'
    }
});

// Fetch the preselected item, and add to the control
var studentSelect = $('#mySelect2');
$.ajax({
    type: 'GET',
    url: '/api/students/s/' + studentId
}).then(function (data) {
    // create the option and append to Select2
    var option = new Option(data.full_name, data.id, true, true);
    studentSelect.append(option).trigger('change');

    // manually trigger the `select2:select` event
    studentSelect.trigger({
        type: 'select2:select',
        params: {
            data: data
        }
    });
});

you can use the following

$(element).select2("data",[ { id: result.id, text: "???? ???? ??????" },
    { id: 2, text: "???? ???? ????" }]);

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to jquery-select2

How can I set the initial value of Select2 when using AJAX? Dynamically add item to jQuery Select2 control that uses AJAX How to set selected value of jquery select2? Styling of Select2 dropdown select boxes How to use placeholder as default value in select2 framework How can I disable selected attribute from select2() dropdown Jquery? Select2 open dropdown on focus How to use Select2 with JSON via Ajax request? Select2() is not a function jQuery select2 get value of select tag?