0

I am using Select2 inside my Asp.net MVC project. I created a weblog. each post has some tags. I am using select2 multiselect to choose tags. In the create page i can search and select tags and save in database.

problem: in edit page also my select2 works fine. but I want to add some tags in edit pageload which the user added in create page. then user can change tags. I can not preselect tags in select2

matius
  • 81
  • 1
  • 3
  • i found the correct answer here [http://stackoverflow.com/a/3740912/6303651](http://stackoverflow.com/a/3740912/6303651) – matius Jan 13 '17 at 11:30

1 Answers1

1

This little jquery function will add options to a select2

$.fn.select2AddOptions = function(options) {
    this.each(function(){
        var $ele = $(this);
        var data = $ele.data('select2');
        if(data) //the $.extend is not recursive change the false for true if needed
            $ele.select2($.extend(false,{},data.options.options,options));
    });
    return this;
}

Then you can use it to add your extra data that are not inside <option> or select2 data:

$('#element').select2AddOptions(
{data:[{id:{{ location.id }},text:'{{ location.name }}',color:'{{ location.color }}'}]}
).trigger('change');

If you need to change selected element:

$('#element').val(['id1','id2']).trigger('change');

I you need that select2 fire his event when you select option you will need to fire event manualy like this:

$('#element').trigger($.Event('select2:select', {params: {data: [...]}}))
greenseed
  • 509
  • 5
  • 10