这属于select2版本4之前的代码
我有一个简单的select2
代码,可以从ajax获取数据
$("#programid").select2({
placeholder: "Select a Program",
allowClear: true,
minimumInputLength: 3,
ajax: {
url: "ajax.php",
dataType: 'json',
quietMillis: 200,
data: function (term, page) {
return {
term: term, //search term
flag: 'selectprogram',
page: page // page number
};
},
results: function (data) {
return {results: data};
}
},
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) { return m; }
});
此代码正常运行,但是,我需要在编辑模式下设置一个值。当用户第一次选择一个值时,它将被保存,当他需要编辑该值时,它必须出现在同一个选择菜单(select2
)中以选择之前选择的值但我找不到方法。
更新:
HTML代码:
<input type="hidden" name="programid" id="programid" class="width-500 validate[required]">
答案 0 :(得分:53)
SELECT2&lt; V4
<input name="mySelect2" type="hidden" id="mySelect2">
$("#mySelect2").select2({
placeholder: "My Select 2",
multiple: false,
minimumInputLength: 1,
ajax: {
url: "/elements/all",
dataType: 'json',
quietMillis: 250,
data: function(term, page) {
return {
q: term,
};
},
results: function(data, page) {
return {results: data};
},
cache: true
},
formatResult: function(element){
return element.text + ' (' + element.id + ')';
},
formatSelection: function(element){
return element.text + ' (' + element.id + ')';
},
escapeMarkup: function(m) {
return m;
}
});
$("#mySelect2").select2('data', { id:"elementID", text: "Hello!"});
如果您使用 select2而不使用AJAX ,您可以执行以下操作:
<select name="mySelect2" id="mySelect2">
<option value="0">One</option>
<option value="1">Two</option>
<option value="2">Three</option>
</select>
/* //////////// "One" will be the selected option */
$('[name=mySelect2]').val("0");
你也可以这样做:
$("#mySelect2").select2("val", "0");
SELECT2 V4
对于 select2 v4 ,您可以直接附加选项/ s,如下所示:
<select id="myMultipleSelect2" multiple="" name="myMultipleSelect2[]">
<option value="TheID" selected="selected">The text</option>
</select>
或者使用JQuery:
var $newOption = $("<option selected='selected'></option>").val("TheID").text("The text")
$("#myMultipleSelect2").append($newOption).trigger('change');
其他例子
$("#myMultipleSelect2").val(5).trigger('change');
答案 1 :(得分:43)
动态设置&#34;选择&#34; Select2组件的值:
$('#inputID').select2('data', {id: 100, a_key: 'Lorem Ipsum'});
第二个参数是具有预期值的对象。
<强>更新强>
这确实有效,只是想注意在新的select2中,&#34; a_key&#34; 是&#34; text&#34; 标准的select2对象。所以:{id: 100, text: 'Lorem Ipsum'}
示例:
$('#all_contacts').select2('data', {id: '123', text: 'res_data.primary_email'});
感谢@NoobishPro
答案 2 :(得分:15)
<强> HTML 强>
<select id="lang" >
<option value="php">php</option>
<option value="asp">asp</option>
<option value="java">java</option>
</select>
<强> JavaScript的:强>
$("#lang").select2().select2('val','asp');
答案 3 :(得分:14)
同样在我尝试的时候,当在select2中使用ajax时,在select2中设置新值的programmatic control方法对我来说不起作用! 现在我编写这些代码来解决问题:
$('#sel')
.empty() //empty select
.append($("<option/>") //add option tag in select
.val("20") //set value for option to post it
.text("nabi")) //set a text for show in select
.val("20") //select option of select2
.trigger("change"); //apply to select2
您可以在此链接中测试完整的示例代码:https://jsfiddle.net/NabiKAZ/2g1qq26v/32/
在此示例代码中,有一个ajax select2,您可以使用按钮设置新值。
$("#btn").click(function() {
$('#sel')
.empty() //empty select
.append($("<option/>") //add option tag in select
.val("20") //set value for option to post it
.text("nabi")) //set a text for show in select
.val("20") //select option of select2
.trigger("change"); //apply to select2
});
$("#sel").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function(params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function(data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function(markup) {
return markup;
}, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
function formatRepo(repo) {
if (repo.loading) return repo.text;
var markup = "<div class='select2-result-repository clearfix'>" +
"<div class='select2-result-repository__avatar'><img src='" + repo.owner.avatar_url + "' /></div>" +
"<div class='select2-result-repository__meta'>" +
"<div class='select2-result-repository__title'>" + repo.full_name + "</div>";
if (repo.description) {
markup += "<div class='select2-result-repository__description'>" + repo.description + "</div>";
}
markup += "<div class='select2-result-repository__statistics'>" +
"<div class='select2-result-repository__forks'><i class='fa fa-flash'></i> " + repo.forks_count + " Forks</div>" +
"<div class='select2-result-repository__stargazers'><i class='fa fa-star'></i> " + repo.stargazers_count + " Stars</div>" +
"<div class='select2-result-repository__watchers'><i class='fa fa-eye'></i> " + repo.watchers_count + " Watchers</div>" +
"</div>" +
"</div></div>";
return markup;
}
function formatRepoSelection(repo) {
return repo.full_name || repo.text;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://select2.org/assets/a7be624d756ba99faa354e455aed250d.css">
<select id="sel" multiple="multiple" class="col-xs-5">
</select>
<button id="btn">Set Default</button>
&#13;
答案 4 :(得分:9)
var $option = $("<option selected></option>").val('1').text("Pick me");
$('#select_id').append($option).trigger('change');
尝试此追加然后选择。在AJAX调用时不会复制该选项。
答案 5 :(得分:7)
在select2
- v4.0.1
的当前版本中,您可以设置如下值:
var $example = $('.js-example-programmatic').select2();
$(".js-programmatic-set-val").on("click", function () { $example.val("CA").trigger("change"); });
// Option 2 if you can't trigger the change event.
var $exampleDestroy = $('.js-example-programmatic-destroy').select2();
$(".js-programmatic-set-val").on("click", function () { $exampleDestroy.val("CA").select2('destroy').select2(); });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
using "trigger(change)"
<select class="js-example-programmatic">
<optgroup label="Alaskan/Hawaiian Time Zone">
<option value="AK">Alaska</option>
<option value="HI">Hawaii</option>
</optgroup>
<optgroup label="Pacific Time Zone">
<option value="CA">California</option>
<option value="NV">Nevada</option>
<option value="OR">Oregon</option>
<option value="WA">Washington</option>
</optgroup>
<optgroup label="Mountain Time Zone">
<option value="AZ">Arizona</option>
<option value="CO">Colorado</option>
<option value="ID">Idaho</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NM">New Mexico</option>
<option value="ND">North Dakota</option>
<option value="UT">Utah</option>
<option value="WY">Wyoming</option>
</optgroup>
<optgroup label="Central Time Zone">
<option value="AL">Alabama</option>
<option value="AR">Arkansas</option>
<option value="IL">Illinois</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="OK">Oklahoma</option>
<option value="SD">South Dakota</option>
<option value="TX">Texas</option>
<option value="TN">Tennessee</option>
<option value="WI">Wisconsin</option>
</optgroup>
<optgroup label="Eastern Time Zone">
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="IN">Indiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="OH">Ohio</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WV">West Virginia</option>
</optgroup>
</select>
using destroy:
<select class="js-example-programmatic">
<optgroup label="Alaskan/Hawaiian Time Zone">
<option value="AK">Alaska</option>
<option value="HI">Hawaii</option>
</optgroup>
<optgroup label="Pacific Time Zone">
<option value="CA">California</option>
<option value="NV">Nevada</option>
<option value="OR">Oregon</option>
<option value="WA">Washington</option>
</optgroup>
<optgroup label="Mountain Time Zone">
<option value="AZ">Arizona</option>
<option value="CO">Colorado</option>
<option value="ID">Idaho</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NM">New Mexico</option>
<option value="ND">North Dakota</option>
<option value="UT">Utah</option>
<option value="WY">Wyoming</option>
</optgroup>
<optgroup label="Central Time Zone">
<option value="AL">Alabama</option>
<option value="AR">Arkansas</option>
<option value="IL">Illinois</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="OK">Oklahoma</option>
<option value="SD">South Dakota</option>
<option value="TX">Texas</option>
<option value="TN">Tennessee</option>
<option value="WI">Wisconsin</option>
</optgroup>
<optgroup label="Eastern Time Zone">
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="IN">Indiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="OH">Ohio</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WV">West Virginia</option>
</optgroup>
</select>
<button class="js-programmatic-set-val">set value</button>
&#13;
答案 6 :(得分:6)
我确实喜欢这个 -
$("#drpServices").select2().val("0").trigger("change");
答案 7 :(得分:5)
我认为您需要initSelection
功能
$("#programid").select2({
placeholder: "Select a Program",
allowClear: true,
minimumInputLength: 3,
ajax: {
url: "ajax.php",
dataType: 'json',
quietMillis: 200,
data: function (term, page) {
return {
term: term, //search term
flag: 'selectprogram',
page: page // page number
};
},
results: function (data) {
return {results: data};
}
},
initSelection: function (element, callback) {
var id = $(element).val();
if (id !== "") {
$.ajax("ajax.php/get_where", {
data: {programid: id},
dataType: "json"
}).done(function (data) {
$.each(data, function (i, value) {
callback({"text": value.text, "id": value.id});
});
;
});
}
},
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) { return m; }
});
答案 8 :(得分:5)
对于Ajax,请使用$(".select2").val("").trigger("change")
。这应该可以解决问题。
答案 9 :(得分:4)
<强> HTML 强>
<select id="lang" >
<option value="php">php</option>
<option value="asp">asp</option>
<option value="java">java</option>
</select>
<强> JS 强>
$("#lang").select2().val('php').trigger('change.select2');
答案 10 :(得分:4)
在 Select2 V.4
中使用$('selector').select2().val(value_to_select).trigger('change');
我认为应该有效
答案 11 :(得分:3)
$("#select_location_id").val(value);
$("#select_location_id").select2().trigger('change');
我用这个简单的代码解决了我的问题。其中#select_location_id是选择框的ID,值是select2框中列出的选项的值。
答案 12 :(得分:2)
设置值并立即触发更改事件。
$('#selectteam').val([183,182]).trigger('change');
答案 13 :(得分:1)
这对我来说很好:
initSelection: function (element, callback) {
var id = $(element).val();
$.ajax("url/" + id, {
dataType: "json"
}).done(function (data) {
var newOption = new Option(data.title, data.id, true, true);
$('#select2_id').append(newOption).trigger('change');
callback({"text": data.title, "id": data.id});
});
},
答案 14 :(得分:1)
$('#inputID').val("100").select2();
在选择当前选择项之一之后应用select2
更合适。
答案 15 :(得分:1)
如果要从ajax获取值,请先调用
$("#select_location_id").val(value);
$("#select_location_id").select2().trigger('change');
使用jquery函数确认ajax调用已完成
$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function(a1, a2, a3, a4){
// the code here will be executed when all four ajax requests resolve.
// a1, a2, a3 and a4 are lists of length 3 containing the response text,
// status, and jqXHR object for each of the four ajax calls respectively.
});
答案 16 :(得分:0)
我将 select2 与 Laravel 的 ajax 源一起使用。在我的情况下,我从页面收到简单的工作循环选项并将选项添加到 select2..
$filtri->stato = [1,2,...];
$('#stato') 是我的带有服务器端负载的 select2
<script>
@foreach ($filtri->stato as $item)
$('#stato').append(new Option("{{\App\Models\stato::find($item)->nome}}",{{$item}}, false, true));
@endforeach
</script>
就我而言,我可以使用 find
方法调用选项文本,但可以使用 ajax 调用来实现
答案 17 :(得分:0)
官方 Select2 documentation 说:
<块引用>对于从AJAX 源接收数据的 Select2 控件,使用 .val() 将不起作用。选项尚不存在,因为在打开控件和/或用户开始搜索之前不会触发 AJAX 请求。
要在 select2
字段中设置值,请在页面呈现期间将 <option>
标签置于 <select>
标签内:
<select id="input-degree">
<option value="1">Art</option>
</select>
加载页面后,您会在 Art
字段中看到 select2
。如果我们点击这个字段,数据将通过 ajax 从服务器获取,并显示其他选项。
答案 18 :(得分:0)
构建@tomloprod答案的基础。您正在使用x-editable,并且有一个select2(v4)字段并且需要预选多个项目,这很奇怪。您可以使用以下代码:
$("#select2field").on("shown", function(e, editable){
$(["test1", "test2", "test3", "test4"]).each(function(k, v){
// Create a DOM Option and pre-select by default~
var newOption = new Option(v.text, v.id, true, true);
// Append it to the select
$(editable.input.$input).append(newOption).trigger('change');
});
});
在这里起作用:
var data = [
{
id: 0,
text: 'enhancement'
},
{
id: 1,
text: 'bug'
},
{
id: 2,
text: 'duplicate'
},
{
id: 3,
text: 'invalid'
},
{
id: 4,
text: 'wontfix'
}
];
$("#select2field").editable({
type: "select2",
url: './',
name: 'select2field',
savenochange: true,
send: 'always',
mode: 'inline',
source: data,
value: "bug, wontfix",
tpl: '<select style="width: 201px;">',
select2: {
width: '201px',
tags: true,
tokenSeparators: [',', ' '],
multiple: true,
data:data
},
success: function(response, newValue) {
console.log("success")
},
error: function(response, newValue) {
if (response.status === 500) {
return 'Service unavailable. Please try later.';
} else {
return response.responseJSON;
}
}
});
var preselect= [
{
id: 1,
text: 'bug'
},
{
id: 4,
text: 'wontfix'
}
];
$("#select2field").on("shown", function(e, editable){
$(preselect).each(function(k, v){
// Create a DOM Option and pre-select by default~
var newOption = new Option(v.text, v.id, true, true);
// Append it to the select
$(editable.input.$input).append(newOption).trigger('change');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap3-editable/css/bootstrap-editable.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap3-editable/js/bootstrap-editable.min.js"></script>
<a id="select2field">bug, wontfix</a>
我猜想,即使您不使用x-editable也可以。我希望htis可以帮助某人。
答案 19 :(得分:0)
这可能有助于某人从AJAX加载select2数据,同时加载要编辑的数据(适用于单选或多选):
在加载表单/模型时:
$.ajax({
type: "POST",
...
success: function (data) {
selectCountries(fixedEncodeURI(data.countries));
}
呼叫选择Select2的数据:
var countrySelect = $('.select_country');
function selectCountries(countries)
{
if (countries) {
$.ajax({
type: 'GET',
url: "/regions/getCountries/",
data: $.param({ 'idsSelected': countries }, true),
}).then(function (data) {
// create the option and append to Select2
$.each(data, function (index, value) {
var option = new Option(value.text, value.id, true, true);
countrySelect.append(option).trigger('change');
console.log(option);
});
// manually trigger the `select2:select` event
countrySelect.trigger({
type: 'select2:select',
params: {
data: data
}
});
});
}
}
,如果您可能在编码方面遇到问题,则可以根据需要进行更改:
function fixedEncodeURI(str) {
return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']').replace(/%22/g,"");
}
答案 20 :(得分:0)
对于多个值,如下所示:
$("#HouseIds").select2("val", @Newtonsoft.Json.JsonConvert.SerializeObject(Model.HouseIds));
这将翻译成这样
$("#HouseIds").select2("val", [35293,49525]);
答案 21 :(得分:0)
您可以使用以下代码:
$("#programid").val(["number:2", "number:3"]).trigger("change");
其中“数字:2”中的2和“数字:3”中的3是对象数组中的ID字段
答案 22 :(得分:0)
美好而轻松:
document.getElementById("select2-id_city-container").innerHTML = "Your Text Here";
然后将id_city
更改为您选择的ID。
编辑:在Glen的评论之后,我意识到我应该解释为什么以及它对我有用:
我让select2
对我的表格非常好。我唯一无法做的工作就是在编辑时显示当前选定的值。它正在搜索第三方API,保存新记录并编辑旧记录。过了一会儿,我意识到我不需要正确设置值,只需要字段内的标签,因为如果用户没有改变字段,则没有任何反应。在搜索并查看很多人遇到问题之后,我决定用纯Javascript制作它。它工作,我发布可能帮助某人。我还建议为它设置一个计时器。
答案 23 :(得分:0)
只是添加给可能与我提出同样问题的其他人。
我试图设置动态加载选项的选定选项(来自AJAX),并尝试根据某些逻辑设置其中一个选项。
我的问题是因为我没有尝试根据需要匹配值的ID设置所选选项,而不是与名称匹配的值!
答案 24 :(得分:0)
有时,select2()
将首先加载,这使得控件不能正确显示先前选择的值。延迟几秒钟可以解决这个问题。
setTimeout(function(){
$('#costcentreid').select2();
},3000);
答案 25 :(得分:0)
在select2 < version4
中,有一个用于远程数据加载的选项initSelection()
,通过它可以在编辑模式下设置输入的初始值。
$("#e6").select2({
placeholder: "Search for a repository",
minimumInputLength: 1,
ajax: {
// instead of writing the function to execute the request we use Select2's convenient helper
url: "https://api.github.com/search/repositories",
dataType: 'json',
quietMillis: 250,
data: function (term, page) {
return {
q: term, // search term
};
},
results: function (data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter the remote JSON data
return { results: data.items };
},
cache: true
},
initSelection: function(element, callback) {
// the input tag has a value attribute preloaded that points to a preselected repository's id
// this function resolves that id attribute to an object that select2 can render
// using its formatResult renderer - that way the repository name is shown preselected
var id = $(element).val();
if (id !== "") {
$.ajax("https://api.github.com/repositories/" + id, {
dataType: "json"
}).done(function(data) { callback(data); });
}
},
formatResult: repoFormatResult, // omitted for brevity, see the source of this page
formatSelection: repoFormatSelection, // omitted for brevity, see the source of this page
dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
});
来源文档:Select2 - 3.5.3
答案 26 :(得分:0)
如果您使用的是输入框,则必须将“multiple”属性设置为“true”。例如,
function Stack(...a){
var stack = new Array(...a);
Object.setPrototypeOf(stack, Stack.prototype);
return stack;
}
Stack.prototype = Object.create(Array.prototype); // now stack has full access to array methods.
Stack.prototype.constructor = Stack; // now Stack is a proper constructor
Stack.prototype.peak = function(){return this[this.length-1]}; // add Stack "only" methods to the Stack.prototype.
var s = new Stack(1,2,3,4,1);
console.log(s.peak());
s[s.length] = 7;
console.log(s.length);
s.push(42);
console.log(s);
console.log(s.length);
答案 27 :(得分:0)
Phan的回答对我有用:
$('#inputID').select2('data', {id: 100, a_key: 'Lorem Ipsum'});
但添加更改会触发事件
$('#inputID').select2('data', {id: 100, a_key: 'Lorem Ipsum'}).change();
答案 28 :(得分:0)
您应该使用:
var autocompleteIds= $("#EventId");
autocompleteIds.empty().append('<option value="Id">Text</option>').val("Id").trigger('change');
// For set multi selected values
var data = [];//Array Ids
var option = [];//Array options of Ids above
autocompleteIds.empty().append(option).val(data).trigger('change');
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR) {
// append the new option
$("#EventId").append('<option value="' + response.id + '">' + response.text + '</option>');
// get a list of selected values if any - or create an empty array
var selectedValues = $("#EventId").val();
if (selectedValues == null) {
selectedValues = new Array();
}
selectedValues.push(response.id); // add the newly created option to the list of selected items
$("#EventId").val(selectedValues).trigger('change'); // have select2 do it's thing
});
答案 29 :(得分:0)
我做了类似的事情来预设select2 ajax下拉列表中的元素
//preset element values
$(id).val(topics);
//topics is an array of format [{"id":"","text":""}, .....]
setTimeout(function(){
ajaxTopicDropdown(id,
2,location.origin+"/api for gettings topics/",
"Pick a topic", true, 5);
},1);
// ajaxtopicDropdown is dry fucntion to get topics for diffrent element and url
答案 30 :(得分:-1)
您可以使用此代码:
$('#country').select2("val", "Pakistan").trigger('change');
将您想要的价值代替巴基斯坦
希望它会起作用:)