Setting initial values on load with Select2 with Ajax
up vote
34
down vote
favorite
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
|
show 2 more comments
up vote
34
down vote
favorite
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
look atinitSelection
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
Trycallback(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 replacedata-initvalue
withvalue
and usecallback(JSON.parse(elementText));
ininitSelection
.
– user1983983
Sep 16 '13 at 13:23
|
show 2 more comments
up vote
34
down vote
favorite
up vote
34
down vote
favorite
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
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
jquery ajax jquery-select2
edited Jan 8 '16 at 20:28
asked Sep 9 '13 at 13:43
Ravi
6102717
6102717
look atinitSelection
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
Trycallback(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 replacedata-initvalue
withvalue
and usecallback(JSON.parse(elementText));
ininitSelection
.
– user1983983
Sep 16 '13 at 13:23
|
show 2 more comments
look atinitSelection
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
Trycallback(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 replacedata-initvalue
withvalue
and usecallback(JSON.parse(elementText));
ininitSelection
.
– 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
|
show 2 more comments
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.
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 meaninitSelection
?
– user657199
Aug 24 '15 at 20:15
it only displays blank or empty
– YXN
Oct 30 '17 at 10:52
add a comment |
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
9
initSelection
is Deprecated in Select2 4.0. This has been replaced by thecurrent
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
add a comment |
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"}]});
2
Is there a way to add anif
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
add a comment |
up vote
13
down vote
Ravi, for 4.0.1-rc.1:
- Add all
<option>
elements inside<select>
. - call
$element.val(yourarray).trigger("change");
afterselect2
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
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
add a comment |
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.
add a comment |
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.
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
add a comment |
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.
add a comment |
up vote
1
down vote
Change the value after the page loads
$('#data').val('').change();
add a comment |
up vote
0
down vote
you can use the following
$(element).select2("data",[ { id: result.id, text: "جابر احمد الصباح" },
{ id: 2, text: "خليل محمد خليل" }]);
add a comment |
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;
}
add a comment |
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");
add a comment |
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.
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 meaninitSelection
?
– user657199
Aug 24 '15 at 20:15
it only displays blank or empty
– YXN
Oct 30 '17 at 10:52
add a comment |
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.
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 meaninitSelection
?
– user657199
Aug 24 '15 at 20:15
it only displays blank or empty
– YXN
Oct 30 '17 at 10:52
add a comment |
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.
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.
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 meaninitSelection
?
– user657199
Aug 24 '15 at 20:15
it only displays blank or empty
– YXN
Oct 30 '17 at 10:52
add a comment |
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 meaninitSelection
?
– 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
add a comment |
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
9
initSelection
is Deprecated in Select2 4.0. This has been replaced by thecurrent
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
add a comment |
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
9
initSelection
is Deprecated in Select2 4.0. This has been replaced by thecurrent
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
add a comment |
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
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
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 thecurrent
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
add a comment |
9
initSelection
is Deprecated in Select2 4.0. This has been replaced by thecurrent
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
add a comment |
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"}]});
2
Is there a way to add anif
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
add a comment |
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"}]});
2
Is there a way to add anif
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
add a comment |
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"}]});
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"}]});
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 anif
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
add a comment |
2
Is there a way to add anif
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
add a comment |
up vote
13
down vote
Ravi, for 4.0.1-rc.1:
- Add all
<option>
elements inside<select>
. - call
$element.val(yourarray).trigger("change");
afterselect2
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
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
add a comment |
up vote
13
down vote
Ravi, for 4.0.1-rc.1:
- Add all
<option>
elements inside<select>
. - call
$element.val(yourarray).trigger("change");
afterselect2
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
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
add a comment |
up vote
13
down vote
up vote
13
down vote
Ravi, for 4.0.1-rc.1:
- Add all
<option>
elements inside<select>
. - call
$element.val(yourarray).trigger("change");
afterselect2
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
Ravi, for 4.0.1-rc.1:
- Add all
<option>
elements inside<select>
. - call
$element.val(yourarray).trigger("change");
afterselect2
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
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
add a comment |
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
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Jan 15 '15 at 20:51
Daniel Díaz Astudillo
13016
13016
add a comment |
add a comment |
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.
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
add a comment |
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.
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
add a comment |
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.
I`ve added
initSelection: function (element, callback) {
callback({ id: 1, text: 'Text' });
}
BUT also
.select2('val', );
at the end.
This solved my issue.
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
add a comment |
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
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Feb 24 '16 at 14:03
gabisajr
213
213
add a comment |
add a comment |
up vote
1
down vote
Change the value after the page loads
$('#data').val('').change();
add a comment |
up vote
1
down vote
Change the value after the page loads
$('#data').val('').change();
add a comment |
up vote
1
down vote
up vote
1
down vote
Change the value after the page loads
$('#data').val('').change();
Change the value after the page loads
$('#data').val('').change();
answered Jul 6 '17 at 14:11
Harry Bosh
1,7811419
1,7811419
add a comment |
add a comment |
up vote
0
down vote
you can use the following
$(element).select2("data",[ { id: result.id, text: "جابر احمد الصباح" },
{ id: 2, text: "خليل محمد خليل" }]);
add a comment |
up vote
0
down vote
you can use the following
$(element).select2("data",[ { id: result.id, text: "جابر احمد الصباح" },
{ id: 2, text: "خليل محمد خليل" }]);
add a comment |
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: "خليل محمد خليل" }]);
you can use the following
$(element).select2("data",[ { id: result.id, text: "جابر احمد الصباح" },
{ id: 2, text: "خليل محمد خليل" }]);
answered Apr 15 '15 at 16:34
Motasem Alsaqqa
2114
2114
add a comment |
add a comment |
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;
}
add a comment |
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;
}
add a comment |
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;
}
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;
}
answered Jan 23 '17 at 18:10
Jonas Sciangula Street
1,1951215
1,1951215
add a comment |
add a comment |
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");
add a comment |
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");
add a comment |
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");
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");
answered Jan 11 at 20:54
Mahfuzur Rahman
12
12
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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
withvalue
and usecallback(JSON.parse(elementText));
ininitSelection
.– user1983983
Sep 16 '13 at 13:23