【问题标题】:Is it possible to set a selection count limit on p:selectManyMenu in Primefaces?是否可以在 Primefaces 中对 p:selectManyMenu 设置选择计数限制?
【发布时间】:2014-02-20 19:28:27
【问题描述】:

我有一个字段,根据屏幕上其他字段的设置,该字段应该允许无限选择、3 个选择或一个选择。

<p:selectManyMenu value="#{orderBean.selectedAddOns}">
    <f:selectItems value="#{catalogBean.addOns}"/>
</p:selectManyMenu>

所以有 10 个可能的附加组件,但其中一个选项(上面未列出的字段)意味着只允许一个附加组件。另一个意味着允许 3 个,对于任何其他选项或根本没有选项,可以选择任何或所有附加组件。那么动态限制可以进行多少选择的最直接的方法是什么?我想要这样当限制为 3 并且用户选择第 4 个时,它会取消选择他们选择的第一个,也就是说,如果他们选择 B、C、D,然后选择 G,则选择变为 C, D, G 如果 B 是他们做出的第一个选择。

【问题讨论】:

    标签: javascript jsf primefaces


    【解决方案1】:

    我会这样做。

    <p:selectManyMenu widgetVar="selectManyMenuWV" 
                      showCheckbox="true">  
       <f:selectItem itemLabel="Option 1" itemValue="1" />  
       <f:selectItem itemLabel="Option 2" itemValue="2" />  
       <f:selectItem itemLabel="Option 3" itemValue="3" />  
       <f:selectItem itemLabel="Option 4" itemValue="4" />  
    </p:selectManyMenu>
    
    <script>              
       $(function() {
          selectManyMenuWV.items.on('click', function() { 
             restrictMenu($(this).text())
          })
          selectManyMenuWV.checkboxes.on('click', function() {                                                       
             restrictMenu($(this).parent().parent().text())
          })
       });
    
       function restrictMenu(notValue) {
          //max selection size
          maxSelectionVar = 4;
          if (maxSelectionVar.length != 0) {
             if (selectManyMenuWV.input.find(':selected').length > maxSelectionVar) {
                selectManyMenuWV.unselectItem(selectManyMenuWV.items.filter(function() {    
                if(selectManyMenuWV.input.find(':selected').eq(0).text() != notValue)                                         
                   return $(this).text() == selectManyMenuWV.input.find(':selected').eq(0).text();  
                else
                  return $(this).text() == selectManyMenuWV.input.find(':selected:last').text();
                 }))
              }
           }
        }
    </script>
    

    注意:这种方法有它的缺点:

    • 它根据项目的文本取消选择。
    • 这只是客户端,这意味着如果有人禁用/入侵了 JS,他将能够选择更多值。我还会在服务器端进行验证。

    可以在github 上找到一个小的工作示例。还有一个online Demo

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-10
      相关资源
      最近更新 更多