How to set selected value of jquery select2?

匿名 (未验证) 提交于 2019-12-03 01:17:01

问题:

This belong to codes prior to select2 version 4

I have a simple code of select2 that get data from 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; } }); 

This code is working, however, I need to set a value on it as if in edit mode. When user select a value first time, it will be saved and when he needs to edit that value it must appear in the same select menu (select2) to select the value previously selected but I can't find a way.

UPDATE:

The HTML code:

Select2 programmatic access does not work with this.

回答1:

To dynamically set the "selected" value of a Select2 component:

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

Whereins the second parameter is an object with expected values.



回答2:

SELECT2


Step #1: HTML

Step #2: Create an instance of 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;       } }); 

Step #3: Set your desired value

$("#mySelect2").select2('data', { id:"elementID", text: "Hello!"}); 

If you use select2 without AJAX you can do as follow:

/* //////////// "One" will be the selected option */ $('[name=mySelect2]').val("0"); 

You can also do so:

$("#mySelect2").select2("val", "0"); 

SELECT2 V4


For select2 v4 you can append directly an option/s as follow:

Or with JQuery:

var $newOption = $("").val("TheID").text("The text")  $("#myMultipleSelect2").append($newOption).trigger('change'); 

other example

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


回答3:

Html:

JavaScript:

$("#lang").select2().select2('val','asp'); 

jsfiddle



回答4:

Also as I tried, when use ajax in select2, the programmatic control methods for set new values in select2 does not work for me! Now I write these code for resolve the problem:

$('#sel')     .empty() //empty select     .append($("") //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 

You can test complete sample code in here link: https://jsfiddle.net/NabiKAZ/2g1qq26v/32/
In this sample code there is a ajax select2 and you can set new value with a button.

$("#btn").click(function() {   $('#sel')     .empty() //empty select     .append($("") //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) " +     "
" + "
" + "
" + repo.full_name + "
"; if (repo.description) { markup += "
" + repo.description + "
"; } markup += "
" + "
" + repo.forks_count + " Forks
" + "
" + repo.stargazers_count + " Stars
" + "
" + repo.watchers_count + " Watchers
" + "
" + "
"; return markup; } function formatRepoSelection(repo) { return repo.full_name || repo.text; }


回答5:

In the current version on select2 - v4.0.1 you can set the value like this:

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(); });
  using "trigger(change)"   using destroy:  


回答6:

I think you need the initSelection function

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


回答7:

var $option = $("").val('1').text("Pick me");  $('#select_id').append($option).trigger('change'); 

Try this append then select. Doesn't duplicate the option upon AJAX call.



回答8:

For Ajax, use $(".select2").val("").trigger("change"). That should solve the problem.



回答9:

HTML

JS

 $("#lang").select2().val('php').trigger('change.select2'); 

source: https://select2.github.io/options.html



回答10:

In Select2 V.4

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

I think it should work



回答11:

I did something like this to preset elements in select2 ajax dropdown

      //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 


回答12:

You should use:

var autocompleteIds= $("#EventId"); autocompleteIds.empty().append('').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('');      // 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 }); 


回答13:

An Phan's answer worked for me:

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

But adding the change trigger the event

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


回答14:

If you are using an Input box, you must set the "multiple" property with its value as "true". For example,



回答15:

In select2 there is the option initSelection() for remote data loading, through which it is possible to set initial value for the input as in edit mode.

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

Source Documentation : Select2 - 3.5.3



回答16:

Sometimes, select2() will be loading firstly, and that makes the control not to show previously selected value correctly. Putting a delay for some seconds can resolve this problem.

setTimeout(function(){                       $('#costcentreid').select2();                },3000); 


回答17:

You can use this code:

    $('#country').select2("val", "Pakistan").trigger('change'); 

Put your desired value instead of Pakistan

Hope It will work :)



回答18:

Just to add to anyone else who may have come up with the same issue with me.

I was trying to set the selected option of my dynamically loaded options (from AJAX) and was trying to set one of the options as selected depending on some logic.

My issue came because I wasn't trying to set the selected option based on the ID which needs to match the value, not the value matching the name!



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!