是否可以在p:selectManyMenu的Primefaces中设置选择计数限制?

时间:2014-02-20 19:28:27

标签: javascript jsf primefaces

我的情况是,我有一个字段,根据屏幕上其他字段的设置,此字段应允许无限选择,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是他们做出的第一个选择。

1 个答案:

答案 0 :(得分: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

希望这有帮助。