如何设置jquery select2的选定值?

这属于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; } }); 

此代码正在工作,但是,我需要设置一个值,就像在编辑模式。 当用户第一次select一个值时,它将被保存,当他需要编辑该值时,它必须出现在相同的select菜单( select2 )中以select先前select的值,但是我找不到方法。

更新:

HTML代码:

 <input type="hidden" name="programid" id="programid" class="width-500 validate[required]"> 

select2编程访问不适用于此。

要dynamic设置Select2组件的“选定”值:

 $('#inputID').select2('data', {id: 100, a_key: 'Lorem Ipsum'}); 

其中第二个参数是具有期望值的对象。

SELECT2 <V4


步骤#1: HTML

 <input name="mySelect2" type="hidden" id="mySelect2"> 

步骤#2: 创build一个Select2的实例

 $("#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; } }); 

步骤#3: 设置你想要的值

 $("#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></option>").val("TheID").text("The text") $("#myMultipleSelect2").append($newOption).trigger('change'); 

另一个例子

 $("select123455").val(5).trigger('change'); 

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

的jsfiddle

也正如我所尝试的,当在select2中使用ajax时,在select2中设置新值的编程控制方法对我来说不起作用! 现在我写这些代码来解决问题:

 $('#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 

你可以在这里testing完整的示例代码链接: https : //jsfiddle.net/NabiKAZ/2g1qq26v/32/
在这个示例代码中有一个ajax select2,你可以用一个button来设置新的值。

 $("#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; } 
 <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> 

select2v4.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(); }); 
 <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> 

我认为你需要initSelectionfunction

 $("#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; } }); 
 var $option = $("<option selected></option>").val('1').text("Pick me"); $('#select_id').append($option).trigger('change'); 

试试这个附加,然后select。 AJAX调用时不会复制该选项。

对于Ajax,使用$(".select2").val("").trigger("change") 。 这应该解决问题。

Select2 V.4中

使用$('selector').select2().val(value_to_select).trigger('change');

我认为它应该工作

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

来源: https : //select2.github.io/options.html

我做了这样的事情来预置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 

你应该使用:

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

一个潘的答案为我工作:

 $('#inputID').select2('data', {id: 100, a_key: 'Lorem Ipsum'}); 

但添加更改触发事件

 $('#inputID').select2('data', {id: 100, a_key: 'Lorem Ipsum'}).change(); 

如果您使用的是input框,则必须将其值设置为“true”的“multiple”属性。 例如,

 <script> $(document).ready(function () { var arr = [{ id: 100, text: 'Lorem Ipsum 1' }, { id: 200, text: 'Lorem Ipsum 2'}]; $('#inputID').select2({ data: arr, width: 200, multiple: true }); }); </script> 

select2 < version4有一个用于远程数据加载的选项initSelection() ,通过它可以在编辑模式下为input设置初始值。

 $("#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