Skip to content

Original select being updated with new option but not marked as selected #4244

@duduklein

Description

@duduklein

I'm using select2 version 4.0.2 rc1.

I'm using select2 with remote data loading. Initially (when my page loads), my select only contains the selected item if something is already selected. otherwise, it's empty.

I then use the remote loading via ajax, which works very well and I can select my desired option. When I look into the "real" select, the new option selected in included, but it's not marked as selected, so my "real" select, still has the first option as "selected".

It seems to be that the issue is in the method ArrayAdapter.prototype.select. The data it receives comes from the loaded select, so it does not contain the "selected" info and it seems that it should be added here. Something like this:

ArrayAdapter.prototype.select = function (data) {
    // NOT SURE HOW YOU HANDLE THE CASE WHERE THE SELECTED OPTION ALREADY EXISTS 
    var $option = this.$element.find('option').filter(function (i, elm) {
      return elm.value == data.id.toString();
    });

    if ($option.length === 0) {
      data.selected = true // ADDED LINE 
      $option = this.option(data);

      this.addOptions($option);
    }

    ArrayAdapter.__super__.select.call(this, data);
  };

Thanks

ps: the cdn link to the version 4.0.2 gives a 404 at the moment: https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/js/select2.js

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions