简体   繁体   English

select2-如果多个选项共享一个值,则返回不正确的所选选项

[英]select2 - incorrect selected option returned if multiple options share a value

I have a select element with multiple optgroups, where it is possible for options in different optgroups to have the same value. 我有一个带有多个optgroup的select元素,其中不同optgroup中的选项可能具有相同的值。 For example (see the 'Apple' and 'Potato' options): 例如(请参阅“ Apple”和“土豆”选项):

<select data-placeholder="Fruit/Veg" id="food_select">
  <option value=""></option>

  <optgroup label="Fruits">
    <option data-params="{'selected_type':'Fruit'}" value="1">Apple</option>
    <option data-params="{'selected_type':'Fruit'}" value="2">Pear</option>
    <option data-params="{'selected_type':'Fruit'}" value="3">Banana</option>
  </optgroup>

  <optgroup label="Veg">
    <option data-params="{'selected_type':'Veg'}" value="1">Potato</option>
    <option data-params="{'selected_type':'Veg'}" value="4">Cabbage</option>
    <option data-params="{'selected_type':'Veg'}" value="5">Bean</option>
  </optgroup>
</select>

With a plain select, attempting to find the selected option with jQuery yields the correct result. 对于普通选择,尝试使用jQuery查找所选选项会产生正确的结果。 $('#food_select').find(:selected)

However, when select2 is applied, and 'Potato' is selected, $('#food_select').find(:selected) returns the 'Apple' option, which is the first option with the value of '1'. 但是,当应用select2并选择了'Potato'时, $('#food_select').find(:selected)返回'Apple'选项,这是第一个值为'1'的选项。

All other selected options work correctly, so it seems select2 is not handling the duplicate values correctly. 所有其他选定的选项均能正常工作,因此似乎select2无法正确处理重复值。 I've created a JSFiddle demonstrating this behaviour, at: http://jsfiddle.net/e57m9cax/ . 我创建了一个展示此行为的JSFiddle,位于: http : //jsfiddle.net/e57m9cax/

Is there a workaround or fix for this behaviour? 是否有解决方法或解决此问题?

I could split this into two separate select elements, but would rather not for UX reasons. 我可以将其拆分为两个单独的选择元素,但宁愿不是出于UX原因。 Any direction would be appreciated. 任何方向将不胜感激。

Thanks. 谢谢。

From Kevin Brown, a collaborator on select2: 在select2的合作者Kevin Brown中:

This is a known issue and because of how the internals are structured for 3.5, it cannot be fixed in the 3.x released. 这是一个已知问题,并且由于3.5的内部结构如何,因此无法在3.x版本中修复。

Luckily it's fixed in 4.0, which will be entering into the first beta shortly 幸运的是,它已在4.0中修复,不久将进入第一个Beta

So the solution to this is to use separate selects until the release of select2 4.0. 因此,解决方案是使用单独的选择直到select2 4.0发行。

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

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