简体   繁体   English

如何使用Chosen.JS多重选择以编程方式选择多个选项

[英]How to programmatically select multiple options with Chosen.JS multiple select

I'm having trouble figuring out how to select multiple values in a multiple select programmatically, with chosenJS/chosen.js and still have the values binded to my ng-model (angularJS). 我很难弄清楚如何使用selectedJS / chosen.js以编程方式在多重选择中选择多个值,并且仍然将值绑定到我的ng-model(angularJS)。

Case: I have a list of users from which some are already saved on the current project. 案例:我有一个用户列表,其中一些用户已经保存在当前项目中。 I want to show these users as selected (but i have no idea how). 我想显示这些用户为选中状态(但我不知道如何)。

I have tried finding the indexs of the users that i want pre-selected and make them "selected" like this: 我尝试查找要预选的用户的索引,并使其变为“ selected”,如下所示:

$('.chzn-container-multi').val(0).trigger('liszt:updated');
$('.chzn-container-multi').val(1).trigger('liszt:updated');
$('.chzn-container-multi').val(2).trigger('liszt:updated');

but this only selects the last one. 但这只会选择最后一个。

Any help would be much appreciated ! 任何帮助将非常感激 !

EDIT 编辑

With help from #Marek Kowalski i was able to select the values in my list, but it wasn't applied to the ng-model connected with my dropdown, anyone have a solution to this? 在#Marek Kowalski的帮助下,我能够选择列表中的值,但是它不适用于与下拉菜单相关联的ng模型,有人对此有解决方案吗?

Selecting multiple values and updating the chosen can be done via this one-liner 通过此单线可以选择多个值并更新所选的值

For version < 1.0 对于版本<1.0

$('.chzn-container-multi').val([0,1,2]).trigger('liszt:updated');

OR for version > 1.0 或版本> 1.0

$('.chzn-container-multi').val([0,1,2]).trigger('chosen:updated');

I'm not sure this is the recommended way of doing it, but the solution which works for me is to manually change the selected="selected" attributes on the options and than trigger the "liszt:updated" event. 我不确定这是否是推荐的方法,但是对我有用的解决方案是手动更改选项上的selected =“ selected”属性,然后触发“ liszt:updated”事件。 To select first 3 options use the following code: 要选择前三个选项,请使用以下代码:

$('select option:nth-child(1)').attr('selected', 'selected');
$('select option:nth-child(2)').attr('selected', 'selected');
$('select option:nth-child(3)').attr('selected', 'selected');
$('select').trigger('liszt:updated');
// since version 1.0 the event name is changed to
$('select').trigger('chosen:updated');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM