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.
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) " + "
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.
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 });
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 });
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.
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!