Ravi
Ravi

Reputation: 877

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.

Upvotes: 37

Views: 120395

Answers (12)

Goddard
Goddard

Reputation: 3069

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
        }
    });
});

Upvotes: 2

Mahfuzur Rahman
Mahfuzur Rahman

Reputation: 141

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");

Upvotes: 0

Harry Bosh
Harry Bosh

Reputation: 3800

Change the value after the page loads

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

Upvotes: 1

MKK
MKK

Reputation: 2559

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"}]});

Upvotes: 15

Jonas Sciangula Street
Jonas Sciangula Street

Reputation: 1893

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;
  }

Upvotes: 0

gabisajr
gabisajr

Reputation: 152

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.

Upvotes: 1

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

Upvotes: 14

user1983983
user1983983

Reputation: 4841

The function which you are specifying as initSelection is called with the initial value as argument. So if value is empty, the function is not called.
When you specifiy value='[{"id":"IN","name":"India"}]' instead of data-initvalue the function gets called and the selection can get initialized.

Upvotes: 5

Motasem Alsaqqa
Motasem Alsaqqa

Reputation: 61

you can use the following

$(element).select2("data",[ { id: result.id, text: "جابر احمد الصباح" },
    { id: 2, text: "خليل محمد خليل" }]);

Upvotes: 0

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.

Upvotes: 12

yanko-belov
yanko-belov

Reputation: 503

I`ve added

initSelection: function (element, callback) {

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

BUT also

.select2('val', []);

at the end.

This solved my issue.

Upvotes: 5

JD - DC TECH
JD - DC TECH

Reputation: 1203

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

Upvotes: 24

Related Questions