Programmatically set the value of a Select2 ajax

天大地大妈咪最大 提交于 2019-11-30 04:26:34

Note: The Question and this Answer are for Select2 v3. Select2 v4 has a very different API than v3.

I think the problem is the initSelection function. Are you using that function to set the initial value? I know the Select2 documentation makes it sound like that is it's purpose, but it also says "Essentially this is an id->object mapping function," and that is not how you have implemented it.

For some reason the call to .trigger('change') causes the initSelection function to get called, which changes the selected value back to "ENABLED_FROM_JS".

Try getting rid of the initSelection function and instead set the initial value using:

autocompleteInput.select2('data', {id:103, label:'ENABLED_FROM_JS'});

jsfiddle

Note: The OP has supplied the formatResult and formatSelection options. As supplied, those callback functions expect the items to have a "label" property, rather than a "text" property. For most users, it should be:

autocompleteInput.select2('data', {id:103, text:'ENABLED_FROM_JS'});

More info on the initSelection function:

If you search through the Select2 documentation for "initSelection", you will see that it is used when the element has an initial value and when the element's .val() function is called. That is because those values consist of only an id and Select2 needs the entire data object (partly so it can display the correct label).

If the Select2 control was displaying a static list, the initSelection function would be easy to write (and it seems like Select2 could supply it for you). In that case, the initSelection function would just have to look up the id in the data list and return the corresponding data object. (I say "return" here, but it doesn't really return the data object; it passes it to a callback function.)

In your case, you probably don't need to supply the initSelection function since your element does not have an initial value (in the html) and you are not going to call its .val() method. Just keep using the .select2('data', ...) method to set values programmatically.

If you were to supply an initSelection function for an autocomplete (that uses ajax), it would probably need to make an ajax call to build the data object.

Note this was tested with version 4+

I was finally able to make progress after finding this discussion: https://groups.google.com/forum/#!topic/select2/TOh3T0yqYr4

The last comment notes a method that I was able to use successfully.

Example:

$("#selectelement").select2("trigger", "select", {
    data: { id: "5" }
});

This seems to be enough information for it to match the ajax data, and set the value correctly. This helped immensely with Custom Data Adapters.

nespapu

To set initial values you need to add the necessary options tag to the select element with jQuery, then define these options as selected with select2's val method and finally trigger select2's 'change' event.

1.-$('#selectElement').append('<option value=someID>optionText</option>');
2.-$('#selectElement').select2('val', someID, true);

The third boolean argument tells select2 to trigger the change event.

For more info, see https://github.com/select2/select2/issues/3057

lucbonnin

Be carreful, there is a mistake in "validated" comment.

autocompleteInput.select2('data', {id:103, label:'ENABLED_FROM_JS'});

The correct way is

autocompleteInput.select2('data', {id:103, text:'ENABLED_FROM_JS'});

Use text instead of label

Valentin Petkov

from their examples https://select2.github.io/examples.html

Programmatic access:

var $example = $(".js-example-programmatic").select2();
var $exampleMulti = $(".js-example-programmatic-multi").select2();
$(".js-programmatic-set-val").on("click", function () { $example.val("CA").trigger("change"); });
$(".js-programmatic-open").on("click", function () { $example.select2("open"); });
$(".js-programmatic-close").on("click", function () { $example.select2("close"); });
$(".js-programmatic-init").on("click", function () { $example.select2(); });
$(".js-programmatic-destroy").on("click", function () { $example.select2("destroy"); });
$(".js-programmatic-multi-set-val").on("click", function () { $exampleMulti.val(["CA", "AL"]).trigger("change"); });
$(".js-programmatic-multi-clear").on("click", function () { $exampleMulti.val(null).trigger("change"); });

If you remove the .trigger('change') from your fiddle it logs Object {id: 1, label: "NEW VALUE"} (need to click twice since the logging is before the value change). Is that what you're looking for?

When using select2 with multiple option, use this construction:

$(element).select2("data", $(element).select2("data").concat(newObject), true);

francisco garcia

this is it:

$("#tag").select2('data', { id:8, title: "Hello!"});
Del Eraser

All you have to do is set the value and then execute: $ ('#myselect').select2 (); or $ ('select').select2 ();. And everything is updated very well.

With Select2 version 4+, there is actually nothing special you need to do. Standard jQuery with a 'change' event trigger at the end will work.

var $select = $("#field");
var items = {id: 1, text: "Name"}; // From AJAX etc
var data = $select.val() || [];    // If you want to merge with existing

$(items).each(function () {
  if(!$select.find("option[value='" + this.id + "']").length) {
    $select.append(new Option(this.text, this.id, true, true));
  }
  data.push(this.id);
});

$select.val(data).trigger('change'); // Standard event notifies select2

There is a basic example in the Select2 documentation: https://select2.org/programmatic-control/add-select-clear-items

Pastlifeuknow

FOR VERSION 3.5.3

    $(".select2").select2('data',{id:taskid,text:taskname}).trigger('change');

Based on John S' answer . Just the the above will work however only if while initializing the select2 the initSelection option is not initialized.

$(".select2").select2({
      //some setup
})

For those still using version 3.5 or even higher ones. Please be sure how you reference select2.js to your page. If you are using async or defer load. This plug-in might behave differently.

Thought to mention.

In my situation I was able to render the preselected option into the HTML server side with PHP.

During my page load, I already knew the option value, so my <select name="team_search"></select> became the following;

        <select name="team_search">
            <?php echo !empty($preselected_team) 
                    ? '<option selected="selected" value="'. $preselected_team->ID .'">' . $preselected_team->team_name . '</option>' 
                    : null ?>
        </select>';

As you can see, when I have a $preselected_team available I render in an option with the selected attribute, value and label set. And, if I don't have a value then not option is rendered.

This approach may not always be possible (and in the case of the OP is not mentioned), but it does come with the added benefit of being ready on page load ahead of JavaScript execution.

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