在select2中预选项目 [英] preselect Item in select2

查看:86
本文介绍了在select2中预选项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Asp.net MVC项目中使用 Select2 .我创建了一个博客.每个帖子都有一些标签.我正在使用select2 multiselect来选择标签.在创建页面中,我可以搜索和选择标签并保存在数据库中.

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.

问题: 在编辑页面中,我的select2也可以正常工作.但是我想在用户添加到创建页面的编辑页面加载中添加一些标签.然后用户可以更改标签. 我无法在select2中预选标签

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

推荐答案

这个小小的jquery函数将为select2添加选项

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;
}

然后,您可以使用它添加不在<option>或select2数据内的额外数据:

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');

我需要select2触发他的事件,当您选择选项时,您需要像这样手动触发事件:

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

这篇关于在select2中预选项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆