preselect Item in select2

﹥>﹥吖頭↗ 提交于 2019-12-25 08:08:04

问题


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


回答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: [...]}}))


来源:https://stackoverflow.com/questions/41620090/preselect-item-in-select2

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