设置多个Select2选项 [英] Set multiple Select2 options

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

问题描述

我有一个创建新对象的表单,这使通过Select2添加多个关键字成为可能.

I have a form to create new Objects, which gives the possibility to add multiple Keywords via a Select2.

我使用Symfony;关键字取自实体.在Select2列表中添加现有关键字效果很好.

I use Symfony ; the Keywords are taken from an entity. Adding existing keyword in the Select2 list work perfectly fine.

现在,我希望为用户提供添加全新关键字的可能性,并使这些新关键字直接出现在Select2列表中.

Now I want to give the user the possibility to add brand new keywords, and that those new keywords directly appears in the Select2 list.

因此,我在新对象表单"上创建了一个添加关键字"按钮,这导致了新关键字"表单(Bootstrap模态窗口).

So I created a "Add Keyword" button on my "new object form", which leads to a "New Keyword" form (a Bootstrap modal window).

用于将新创建的关键字添加到Select2列表的Javascript如下:

The Javascript used to add the newly created keyword to the Select2 list is the following:

function OnSuccess(result){
    var keywordsSelected = new Array($("#object_keywords").select2("val")); 
    $('#object_keywords').append('<option value="'+result.id+'" selected="selected">'+result.name+'</option>');
    keywordsSelected.push(result.id);
    $("#object_keywords").select2("val", keywordsSelected); // 
    $('#addKeyword').modal('hide');
}

现在这很奇怪:

  • 我单击添加关键字"按钮,在新关键字"表单中填写新关键字的名称,我确认,新关键字已添加到Select2列表中->一切都很好
  • 我下次也做同样的事情->一切都很好,第二个新关键字被添加到前一个关键字附近的Select2列表中
  • 我第三次执行相同的操作,并且...添加了第三个关键字,但第一个关键字消失了

即使2个fisrt是数据库中已经存在的旧"关键字,此操作也会追加,但是如果我仅添加旧"关键字(我可以添加任意多个),则不会追加.

This appends even if the 2 fisrt are "old" keywords already existing in the DB, but this doesn't append if I add only "old" keywords (I can add as many as I want).

您是否知道问题可能来自何处?

Do you have any idea where the problem could come from?

推荐答案

好吧...

我继续搜索,偶然发现了一些似乎有用的东西(即,我还没有找到一个行不通的情况).

I continued to search and by chance I found something which seems to work (i.e. I didn't find a case where it doesn't, yet).

我更改了行的顺序,并添加了"clear Select2"指令:

I changed the order of the lines and added a "clear Select2" instruction:

function OnSuccess(result){
    $('#addKeyword').modal('hide');  
    $('#webobs_eventbundle_event_keywords').append('<option value="'+result.id+'" selected="selected">'+result.name+'</option>'); // Add the new Keyword in the list
    var keywordsSelected = $("#webobs_eventbundle_event_keywords").select2("val");
    keywordsSelected.push(result.id);
    $("#webobs_eventbundle_event_keywords").select2("val", null);
    $("#webobs_eventbundle_event_keywords").select2("val", keywordsSelected);     
}

无论如何,我仍然对您对此问题的看法感兴趣,因为我没有真正看到此代码起作用的原因,而不是第一个...

Anyway, I'm still interested in you opinion about this problem, because I don't really see the reason why this code works and not the first one...

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

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