Setting initial values on load with Select2 with Ajax
Asked Answered
P

12

37

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.

Parturition answered 9/9, 2013 at 13:43 Comment(6)
look at initSelection optionSwanee
I had tried that without success (pls chk my description). do you see any issues in how I did? can you help me clear that?Parturition
Try callback(JSON.parse(elementText));Swanee
Try to replace data-initvalue with value and use callback(JSON.parse(elementText)); in initSelection.Supremacy
@Supremacy Thank you so much. Your suggestion did the trick. I replaced var elementText = JSON.parse($(element).val()); instead of changing the callback. You didn't put your suggestion as answer, so I can't mark your answer as accepted one but I have upvoted it.Parturition
You are welcome, I added my suggestion as an answer. Glad to help you.Supremacy
S
5

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.

Supremacy answered 19/9, 2013 at 11:11 Comment(4)
I have an issue with using the value attribute as this gets submitted even with blank. i tried to keep it blank and pull this dynamically from data-initvalue in the select2 params but that does not work. is there a way i can do without defining the value attribute?Parturition
What do you mean by it gets submitted even with blank? When you clear the value, the initially specified value gets submitted?Supremacy
Do you mean initSelection?Inexpressible
it only displays blank or emptyOberg
T
24

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

Tubular answered 16/1, 2014 at 19:19 Comment(3)
initSelection is Deprecated in Select2 4.0. This has been replaced by the current method on the data adapter and is only available in the full builds.Warr
@PaulT.Rawkeen so the ability to have a pre-selection has been deprecated and made more confusing? wtf? I've been trying to pre-select multiple values for hours now and never saw that in the docs. This is absurd.Leopard
Doesn't help that half of the documentation is "being written". Honestly, if you haven't written the documentation yet, the version is not ready to be released.Denadenae
S
15

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"}]});
Sclerenchyma answered 25/12, 2013 at 9:48 Comment(3)
Is there a way to add an if on this callback?Emptor
i had a problem with the plugin, only adds the first array, ignore the rest of themAwed
The AJAX call doesn't happen.Benilda
A
14

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

Aetolia answered 11/11, 2015 at 23:10 Comment(2)
NOTE: I also try to directly push it without add in option, but it's not work. You should add in both option and push + triggerKloof
Struggled for 3 hours before stumbling upon this sweet piece of code. Thanks!Buddle
P
12

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.

Polenta answered 15/1, 2015 at 20:51 Comment(0)
S
5

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.

Supremacy answered 19/9, 2013 at 11:11 Comment(4)
I have an issue with using the value attribute as this gets submitted even with blank. i tried to keep it blank and pull this dynamically from data-initvalue in the select2 params but that does not work. is there a way i can do without defining the value attribute?Parturition
What do you mean by it gets submitted even with blank? When you clear the value, the initially specified value gets submitted?Supremacy
Do you mean initSelection?Inexpressible
it only displays blank or emptyOberg
C
5

I`ve added

initSelection: function (element, callback) {

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

BUT also

.select2('val', []);

at the end.

This solved my issue.

Caylor answered 7/1, 2015 at 13:15 Comment(2)
A question after more than a year; why exactly is that .select2('val', []) part is necessary? I'm a little too lazy to go through the source code.Feign
@Feign This is required to clear out the current value in the field. Otherwise the select2 will append the values.Studer
N
1
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.

Northerner answered 24/2, 2016 at 14:3 Comment(0)
S
1

Change the value after the page loads

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

Streeto answered 6/7, 2017 at 14:11 Comment(0)
G
1

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
        }
    });
});
Gil answered 11/2, 2021 at 17:2 Comment(0)
A
0

you can use the following

$(element).select2("data",[ { id: result.id, text: "جابر احمد الصباح" },
    { id: 2, text: "خليل محمد خليل" }]);
Astringent answered 15/4, 2015 at 16:34 Comment(0)
P
0

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;
  }
Papillary answered 23/1, 2017 at 18:10 Comment(0)
B
0

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");
Bismuthinite answered 11/1, 2018 at 20:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.