Setting initial values on load with Select2 with Ajax











up vote
34
down vote

favorite
5












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.










share|improve this question
























  • look at initSelection option
    – Arun P Johny
    Sep 9 '13 at 13:45










  • 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?
    – Ravi
    Sep 9 '13 at 14:24










  • Try callback(JSON.parse(elementText));
    – Arun P Johny
    Sep 9 '13 at 14:26










  • Nope. No luck yet :(
    – Ravi
    Sep 9 '13 at 15:15






  • 3




    Try to replace data-initvalue with value and use callback(JSON.parse(elementText)); in initSelection.
    – user1983983
    Sep 16 '13 at 13:23















up vote
34
down vote

favorite
5












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.










share|improve this question
























  • look at initSelection option
    – Arun P Johny
    Sep 9 '13 at 13:45










  • 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?
    – Ravi
    Sep 9 '13 at 14:24










  • Try callback(JSON.parse(elementText));
    – Arun P Johny
    Sep 9 '13 at 14:26










  • Nope. No luck yet :(
    – Ravi
    Sep 9 '13 at 15:15






  • 3




    Try to replace data-initvalue with value and use callback(JSON.parse(elementText)); in initSelection.
    – user1983983
    Sep 16 '13 at 13:23













up vote
34
down vote

favorite
5









up vote
34
down vote

favorite
5






5





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.










share|improve this question















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.







jquery ajax jquery-select2






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 8 '16 at 20:28

























asked Sep 9 '13 at 13:43









Ravi

6102717




6102717












  • look at initSelection option
    – Arun P Johny
    Sep 9 '13 at 13:45










  • 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?
    – Ravi
    Sep 9 '13 at 14:24










  • Try callback(JSON.parse(elementText));
    – Arun P Johny
    Sep 9 '13 at 14:26










  • Nope. No luck yet :(
    – Ravi
    Sep 9 '13 at 15:15






  • 3




    Try to replace data-initvalue with value and use callback(JSON.parse(elementText)); in initSelection.
    – user1983983
    Sep 16 '13 at 13:23


















  • look at initSelection option
    – Arun P Johny
    Sep 9 '13 at 13:45










  • 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?
    – Ravi
    Sep 9 '13 at 14:24










  • Try callback(JSON.parse(elementText));
    – Arun P Johny
    Sep 9 '13 at 14:26










  • Nope. No luck yet :(
    – Ravi
    Sep 9 '13 at 15:15






  • 3




    Try to replace data-initvalue with value and use callback(JSON.parse(elementText)); in initSelection.
    – user1983983
    Sep 16 '13 at 13:23
















look at initSelection option
– Arun P Johny
Sep 9 '13 at 13:45




look at initSelection option
– Arun P Johny
Sep 9 '13 at 13:45












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?
– Ravi
Sep 9 '13 at 14:24




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?
– Ravi
Sep 9 '13 at 14:24












Try callback(JSON.parse(elementText));
– Arun P Johny
Sep 9 '13 at 14:26




Try callback(JSON.parse(elementText));
– Arun P Johny
Sep 9 '13 at 14:26












Nope. No luck yet :(
– Ravi
Sep 9 '13 at 15:15




Nope. No luck yet :(
– Ravi
Sep 9 '13 at 15:15




3




3




Try to replace data-initvalue with value and use callback(JSON.parse(elementText)); in initSelection.
– user1983983
Sep 16 '13 at 13:23




Try to replace data-initvalue with value and use callback(JSON.parse(elementText)); in initSelection.
– user1983983
Sep 16 '13 at 13:23












11 Answers
11






active

oldest

votes

















up vote
5
down vote



accepted










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.






share|improve this answer























  • 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?
    – Ravi
    Sep 26 '13 at 17:53










  • What do you mean by it gets submitted even with blank? When you clear the value, the initially specified value gets submitted?
    – user1983983
    Sep 26 '13 at 18:38










  • Do you mean initSelection?
    – user657199
    Aug 24 '15 at 20:15










  • it only displays blank or empty
    – YXN
    Oct 30 '17 at 10:52


















up vote
24
down vote













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






share|improve this answer



















  • 9




    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.
    – Paul T. Rawkeen
    Aug 13 '15 at 21:39






  • 15




    @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.
    – The Puma
    Oct 15 '15 at 23:42








  • 6




    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.
    – Captain Hypertext
    Feb 22 '16 at 13:12


















up vote
15
down vote













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





share|improve this answer



















  • 2




    Is there a way to add an if on this callback?
    – Michel Ayres
    Jul 7 '14 at 18:31










  • i had a problem with the plugin, only adds the first array, ignore the rest of them
    – kscius
    May 7 '17 at 6:33










  • @kscius i updated example. please try again
    – Misha Kobrin
    May 12 '17 at 16:43


















up vote
13
down vote













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






share|improve this answer





















  • 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 + trigger
    – Sruit A.Suk
    May 17 '16 at 17:34


















up vote
11
down vote













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.






share|improve this answer




























    up vote
    4
    down vote













    I`ve added



    initSelection: function (element, callback) {

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


    BUT also



    .select2('val', );


    at the end.



    This solved my issue.






    share|improve this answer





















    • 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.
      – Hkan
      Jan 21 '16 at 16:49










    • @Hkan This is required to clear out the current value in the field. Otherwise the select2 will append the values.
      – stotrami
      Apr 8 '16 at 20:11


















    up vote
    1
    down vote













    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.






    share|improve this answer




























      up vote
      1
      down vote













      Change the value after the page loads



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






      share|improve this answer




























        up vote
        0
        down vote













        you can use the following



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





        share|improve this answer




























          up vote
          0
          down vote













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





          share|improve this answer




























            up vote
            0
            down vote













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





            share|improve this answer





















              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f18699641%2fsetting-initial-values-on-load-with-select2-with-ajax%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              11 Answers
              11






              active

              oldest

              votes








              11 Answers
              11






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              5
              down vote



              accepted










              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.






              share|improve this answer























              • 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?
                – Ravi
                Sep 26 '13 at 17:53










              • What do you mean by it gets submitted even with blank? When you clear the value, the initially specified value gets submitted?
                – user1983983
                Sep 26 '13 at 18:38










              • Do you mean initSelection?
                – user657199
                Aug 24 '15 at 20:15










              • it only displays blank or empty
                – YXN
                Oct 30 '17 at 10:52















              up vote
              5
              down vote



              accepted










              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.






              share|improve this answer























              • 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?
                – Ravi
                Sep 26 '13 at 17:53










              • What do you mean by it gets submitted even with blank? When you clear the value, the initially specified value gets submitted?
                – user1983983
                Sep 26 '13 at 18:38










              • Do you mean initSelection?
                – user657199
                Aug 24 '15 at 20:15










              • it only displays blank or empty
                – YXN
                Oct 30 '17 at 10:52













              up vote
              5
              down vote



              accepted







              up vote
              5
              down vote



              accepted






              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.






              share|improve this answer














              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.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Aug 26 '15 at 10:00

























              answered Sep 19 '13 at 11:11









              user1983983

              4,18421021




              4,18421021












              • 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?
                – Ravi
                Sep 26 '13 at 17:53










              • What do you mean by it gets submitted even with blank? When you clear the value, the initially specified value gets submitted?
                – user1983983
                Sep 26 '13 at 18:38










              • Do you mean initSelection?
                – user657199
                Aug 24 '15 at 20:15










              • it only displays blank or empty
                – YXN
                Oct 30 '17 at 10:52


















              • 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?
                – Ravi
                Sep 26 '13 at 17:53










              • What do you mean by it gets submitted even with blank? When you clear the value, the initially specified value gets submitted?
                – user1983983
                Sep 26 '13 at 18:38










              • Do you mean initSelection?
                – user657199
                Aug 24 '15 at 20:15










              • it only displays blank or empty
                – YXN
                Oct 30 '17 at 10:52
















              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?
              – Ravi
              Sep 26 '13 at 17:53




              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?
              – Ravi
              Sep 26 '13 at 17:53












              What do you mean by it gets submitted even with blank? When you clear the value, the initially specified value gets submitted?
              – user1983983
              Sep 26 '13 at 18:38




              What do you mean by it gets submitted even with blank? When you clear the value, the initially specified value gets submitted?
              – user1983983
              Sep 26 '13 at 18:38












              Do you mean initSelection?
              – user657199
              Aug 24 '15 at 20:15




              Do you mean initSelection?
              – user657199
              Aug 24 '15 at 20:15












              it only displays blank or empty
              – YXN
              Oct 30 '17 at 10:52




              it only displays blank or empty
              – YXN
              Oct 30 '17 at 10:52












              up vote
              24
              down vote













              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






              share|improve this answer



















              • 9




                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.
                – Paul T. Rawkeen
                Aug 13 '15 at 21:39






              • 15




                @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.
                – The Puma
                Oct 15 '15 at 23:42








              • 6




                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.
                – Captain Hypertext
                Feb 22 '16 at 13:12















              up vote
              24
              down vote













              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






              share|improve this answer



















              • 9




                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.
                – Paul T. Rawkeen
                Aug 13 '15 at 21:39






              • 15




                @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.
                – The Puma
                Oct 15 '15 at 23:42








              • 6




                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.
                – Captain Hypertext
                Feb 22 '16 at 13:12













              up vote
              24
              down vote










              up vote
              24
              down vote









              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






              share|improve this answer














              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







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Jan 24 '14 at 18:41

























              answered Jan 16 '14 at 19:19









              JD - DC TECH

              960812




              960812








              • 9




                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.
                – Paul T. Rawkeen
                Aug 13 '15 at 21:39






              • 15




                @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.
                – The Puma
                Oct 15 '15 at 23:42








              • 6




                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.
                – Captain Hypertext
                Feb 22 '16 at 13:12














              • 9




                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.
                – Paul T. Rawkeen
                Aug 13 '15 at 21:39






              • 15




                @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.
                – The Puma
                Oct 15 '15 at 23:42








              • 6




                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.
                – Captain Hypertext
                Feb 22 '16 at 13:12








              9




              9




              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.
              – Paul T. Rawkeen
              Aug 13 '15 at 21:39




              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.
              – Paul T. Rawkeen
              Aug 13 '15 at 21:39




              15




              15




              @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.
              – The Puma
              Oct 15 '15 at 23:42






              @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.
              – The Puma
              Oct 15 '15 at 23:42






              6




              6




              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.
              – Captain Hypertext
              Feb 22 '16 at 13:12




              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.
              – Captain Hypertext
              Feb 22 '16 at 13:12










              up vote
              15
              down vote













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





              share|improve this answer



















              • 2




                Is there a way to add an if on this callback?
                – Michel Ayres
                Jul 7 '14 at 18:31










              • i had a problem with the plugin, only adds the first array, ignore the rest of them
                – kscius
                May 7 '17 at 6:33










              • @kscius i updated example. please try again
                – Misha Kobrin
                May 12 '17 at 16:43















              up vote
              15
              down vote













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





              share|improve this answer



















              • 2




                Is there a way to add an if on this callback?
                – Michel Ayres
                Jul 7 '14 at 18:31










              • i had a problem with the plugin, only adds the first array, ignore the rest of them
                – kscius
                May 7 '17 at 6:33










              • @kscius i updated example. please try again
                – Misha Kobrin
                May 12 '17 at 16:43













              up vote
              15
              down vote










              up vote
              15
              down vote









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





              share|improve this answer














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






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited May 12 '17 at 16:42

























              answered Dec 25 '13 at 9:48









              Misha Kobrin

              1,0491212




              1,0491212








              • 2




                Is there a way to add an if on this callback?
                – Michel Ayres
                Jul 7 '14 at 18:31










              • i had a problem with the plugin, only adds the first array, ignore the rest of them
                – kscius
                May 7 '17 at 6:33










              • @kscius i updated example. please try again
                – Misha Kobrin
                May 12 '17 at 16:43














              • 2




                Is there a way to add an if on this callback?
                – Michel Ayres
                Jul 7 '14 at 18:31










              • i had a problem with the plugin, only adds the first array, ignore the rest of them
                – kscius
                May 7 '17 at 6:33










              • @kscius i updated example. please try again
                – Misha Kobrin
                May 12 '17 at 16:43








              2




              2




              Is there a way to add an if on this callback?
              – Michel Ayres
              Jul 7 '14 at 18:31




              Is there a way to add an if on this callback?
              – Michel Ayres
              Jul 7 '14 at 18:31












              i had a problem with the plugin, only adds the first array, ignore the rest of them
              – kscius
              May 7 '17 at 6:33




              i had a problem with the plugin, only adds the first array, ignore the rest of them
              – kscius
              May 7 '17 at 6:33












              @kscius i updated example. please try again
              – Misha Kobrin
              May 12 '17 at 16:43




              @kscius i updated example. please try again
              – Misha Kobrin
              May 12 '17 at 16:43










              up vote
              13
              down vote













              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






              share|improve this answer





















              • 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 + trigger
                – Sruit A.Suk
                May 17 '16 at 17:34















              up vote
              13
              down vote













              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






              share|improve this answer





















              • 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 + trigger
                – Sruit A.Suk
                May 17 '16 at 17:34













              up vote
              13
              down vote










              up vote
              13
              down vote









              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






              share|improve this answer












              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







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Nov 11 '15 at 23:10









              Lazaro Fernandes Lima

              634616




              634616












              • 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 + trigger
                – Sruit A.Suk
                May 17 '16 at 17:34


















              • 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 + trigger
                – Sruit A.Suk
                May 17 '16 at 17:34
















              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 + trigger
              – Sruit A.Suk
              May 17 '16 at 17:34




              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 + trigger
              – Sruit A.Suk
              May 17 '16 at 17:34










              up vote
              11
              down vote













              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.






              share|improve this answer

























                up vote
                11
                down vote













                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.






                share|improve this answer























                  up vote
                  11
                  down vote










                  up vote
                  11
                  down vote









                  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.






                  share|improve this answer












                  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.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 15 '15 at 20:51









                  Daniel Díaz Astudillo

                  13016




                  13016






















                      up vote
                      4
                      down vote













                      I`ve added



                      initSelection: function (element, callback) {

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


                      BUT also



                      .select2('val', );


                      at the end.



                      This solved my issue.






                      share|improve this answer





















                      • 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.
                        – Hkan
                        Jan 21 '16 at 16:49










                      • @Hkan This is required to clear out the current value in the field. Otherwise the select2 will append the values.
                        – stotrami
                        Apr 8 '16 at 20:11















                      up vote
                      4
                      down vote













                      I`ve added



                      initSelection: function (element, callback) {

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


                      BUT also



                      .select2('val', );


                      at the end.



                      This solved my issue.






                      share|improve this answer





















                      • 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.
                        – Hkan
                        Jan 21 '16 at 16:49










                      • @Hkan This is required to clear out the current value in the field. Otherwise the select2 will append the values.
                        – stotrami
                        Apr 8 '16 at 20:11













                      up vote
                      4
                      down vote










                      up vote
                      4
                      down vote









                      I`ve added



                      initSelection: function (element, callback) {

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


                      BUT also



                      .select2('val', );


                      at the end.



                      This solved my issue.






                      share|improve this answer












                      I`ve added



                      initSelection: function (element, callback) {

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


                      BUT also



                      .select2('val', );


                      at the end.



                      This solved my issue.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Jan 7 '15 at 13:15









                      belov91

                      1831312




                      1831312












                      • 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.
                        – Hkan
                        Jan 21 '16 at 16:49










                      • @Hkan This is required to clear out the current value in the field. Otherwise the select2 will append the values.
                        – stotrami
                        Apr 8 '16 at 20:11


















                      • 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.
                        – Hkan
                        Jan 21 '16 at 16:49










                      • @Hkan This is required to clear out the current value in the field. Otherwise the select2 will append the values.
                        – stotrami
                        Apr 8 '16 at 20:11
















                      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.
                      – Hkan
                      Jan 21 '16 at 16:49




                      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.
                      – Hkan
                      Jan 21 '16 at 16:49












                      @Hkan This is required to clear out the current value in the field. Otherwise the select2 will append the values.
                      – stotrami
                      Apr 8 '16 at 20:11




                      @Hkan This is required to clear out the current value in the field. Otherwise the select2 will append the values.
                      – stotrami
                      Apr 8 '16 at 20:11










                      up vote
                      1
                      down vote













                      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.






                      share|improve this answer

























                        up vote
                        1
                        down vote













                        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.






                        share|improve this answer























                          up vote
                          1
                          down vote










                          up vote
                          1
                          down vote









                          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.






                          share|improve this answer












                          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.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Feb 24 '16 at 14:03









                          gabisajr

                          213




                          213






















                              up vote
                              1
                              down vote













                              Change the value after the page loads



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






                              share|improve this answer

























                                up vote
                                1
                                down vote













                                Change the value after the page loads



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






                                share|improve this answer























                                  up vote
                                  1
                                  down vote










                                  up vote
                                  1
                                  down vote









                                  Change the value after the page loads



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






                                  share|improve this answer












                                  Change the value after the page loads



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







                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Jul 6 '17 at 14:11









                                  Harry Bosh

                                  1,7811419




                                  1,7811419






















                                      up vote
                                      0
                                      down vote













                                      you can use the following



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





                                      share|improve this answer

























                                        up vote
                                        0
                                        down vote













                                        you can use the following



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





                                        share|improve this answer























                                          up vote
                                          0
                                          down vote










                                          up vote
                                          0
                                          down vote









                                          you can use the following



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





                                          share|improve this answer












                                          you can use the following



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






                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Apr 15 '15 at 16:34









                                          Motasem Alsaqqa

                                          2114




                                          2114






















                                              up vote
                                              0
                                              down vote













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





                                              share|improve this answer

























                                                up vote
                                                0
                                                down vote













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





                                                share|improve this answer























                                                  up vote
                                                  0
                                                  down vote










                                                  up vote
                                                  0
                                                  down vote









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





                                                  share|improve this answer












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






                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Jan 23 '17 at 18:10









                                                  Jonas Sciangula Street

                                                  1,1951215




                                                  1,1951215






















                                                      up vote
                                                      0
                                                      down vote













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





                                                      share|improve this answer

























                                                        up vote
                                                        0
                                                        down vote













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





                                                        share|improve this answer























                                                          up vote
                                                          0
                                                          down vote










                                                          up vote
                                                          0
                                                          down vote









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





                                                          share|improve this answer












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






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Jan 11 at 20:54









                                                          Mahfuzur Rahman

                                                          12




                                                          12






























                                                              draft saved

                                                              draft discarded




















































                                                              Thanks for contributing an answer to Stack Overflow!


                                                              • Please be sure to answer the question. Provide details and share your research!

                                                              But avoid



                                                              • Asking for help, clarification, or responding to other answers.

                                                              • Making statements based on opinion; back them up with references or personal experience.


                                                              To learn more, see our tips on writing great answers.





                                                              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                              Please pay close attention to the following guidance:


                                                              • Please be sure to answer the question. Provide details and share your research!

                                                              But avoid



                                                              • Asking for help, clarification, or responding to other answers.

                                                              • Making statements based on opinion; back them up with references or personal experience.


                                                              To learn more, see our tips on writing great answers.




                                                              draft saved


                                                              draft discarded














                                                              StackExchange.ready(
                                                              function () {
                                                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f18699641%2fsetting-initial-values-on-load-with-select2-with-ajax%23new-answer', 'question_page');
                                                              }
                                                              );

                                                              Post as a guest















                                                              Required, but never shown





















































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown

































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown







                                                              Popular posts from this blog

                                                              404 Error Contact Form 7 ajax form submitting

                                                              How to know if a Active Directory user can login interactively

                                                              TypeError: fit_transform() missing 1 required positional argument: 'X'