Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set data after init #3185

Closed
Knoxvillekm opened this issue Mar 23, 2015 · 8 comments
Closed

Set data after init #3185

Knoxvillekm opened this issue Mar 23, 2015 · 8 comments

Comments

@Knoxvillekm
Copy link

select2 4.0rc2
I need method to set data after init, like ajax search result with properties from processResults. Can you help me?

Example:

$('select').select2({
  ... ,
  ajax {
    ... ,
    processResults: function (data) {
      return { 
        results: $.map(data, function (item) {
          return {
            id: item.id,
            text: item.text,
            full: item.full
          }
        }) 
      };
    },
    ...
  },
  initData: [ { id: 1, text: 'text', full: true } ],
  ...
});

or

  $('select').select2({ ... });
  $('select').select2('data', [ { id: 1, text: 'text', full: true } ]);
@rolfeisenhut
Copy link

hello,
i've the same request, requiring updating of the data after initializing.

@rolfeisenhut
Copy link

there is a sample for version 2.3.5.2. for loading data via a function,
but this sample does not work in 2.4.

$("#e10_4").select2({
    data:function() { return { text:'tag', results: data }; },
    formatSelection: format,
    formatResult: format
});

@jumale
Copy link

jumale commented Mar 24, 2015

+1
I need it too.
There are select boxes, which have a dynamic list of options (depends on some external parameters).
Currently I have to do it in a way like:

$('#my_select').select2({
    data: [{id: 1, text: 'a'}, {id: 2, text: 'b'}, {id: 3, text: 'c'}] // load all the possible options
})
someExternalParameters.onChange = function () {
    var activeOptions = defineBasedOnExternalParameters();
    $('#my_select').find('option').each(function(){
        if (-1 === activeOptions.indexOf($(this).val())) {
            $(this).hide()
        } else {
            $(this).show()
        }
    });
}

but it's not so good solution as:

$('#my_select').select2({
    data: function () {
        var options = defineBasedOnExternalParameters();
        return options;
    }
})

@e-frank e-frank mentioned this issue Mar 30, 2015
@kevin-brown
Copy link
Member

Right now passing data in when initializing Select2 is a shortcut that is equivalent to creating an <option> for each object passed in. This is why when you initialize Select2 multiple times with similar items, new <option> tags are created.

So a way that you can work around this, which is similar to what you would do if you were working with a native <select>, is to remove all of the <option> elements before initializing Select2.

$("select option").remove(); or // .empty()

If you need to preserve existing selections, then you can filter those out as well

$("select option:not(:selected)").remove();

@Knoxvillekm
Copy link
Author

Can you add this code:

    // Set initial data
    var initData = this.options.get('initData');
    if (initData && $.isArray(initData)) {
      initData.forEach(function(item) {
        var $option = self.dataAdapter.option(item)[0];
        $option.selected = true;
        self.dataAdapter.addOptions($option);
      }); 
    }

to project before:

    // Set the initial state
    this.dataAdapter.current(function (initialData) {
      self.trigger('selection:update', {
        data: initialData
      });
    });

@isAlmogK
Copy link

@kevin-brown thanks

@MrHubble
Copy link

I found this answer on Stackoverflow by Kevin useful

@doapp-ryanp
Copy link

doapp-ryanp commented May 8, 2017

@MrHubble I can get the<option>s removed, but .change() does not re-paint with the current <option>s defined in the DOM. Any ideas?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants