Reputation: 81
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
Upvotes: 0
Views: 995
Reputation: 529
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: [...]}}))
Upvotes: 1