DataTable 中的每一行都有复选框。如何在选中新复选框时取消选中前一个复选框

Each row in DataTable has checkboxes .How to uncheck the previous checked box, on check of new checkbox

单击“添加”按钮后,将创建带有文本框和复选框的空行。我必须在文本框中输入详细信息,但只应选中一个复选框。现在我可以选中所有复选框。但是如果一个被选中,其他复选框应该被取消选中。

<p:commandButton value="Add"
                        actionListener="#{createReturns.addReturnBodyToList}" ajax="true"
                        update="bodyTable messages" style="margin-bottom:10px;"/>
<p:dataTable id="bodyTable" value="#{createReturns.returnBodyList}"
                        var="returnBody">
<p:column headerText="Element Name" style="width:250px;">
                            <p:inputText id="elementName" value="#{returnBody.elementName}"
                                style="width:240px;" />

                        </p:column>
<p:column headerText="KeyColumn" style="width:80px">
                            <p:selectBooleanCheckbox value="#{returnBody.keyColumn}" id="key">

                                <p:ajax listener="#{createReturns.toggleCheckBox()}"
                                    event="click" update="key">
                                    <f:attribute name="element" value="#{returnBody.elementName}"></f:attribute>
                                </p:ajax>
                            </p:selectBooleanCheckbox>
                        </p:column>
</p:datatable>

用于在数据表中添加空行的命令按钮的动作侦听器

    public void addReturnBodyToList() {

        returnBody = new ReturnBody();
        returnBodyList.add(returnBody);

    }

ajax 侦听器取消选中 bean 中的其他复选框

public void toggleCheckBox(ActionEvent actionEvent) {
        String elementName = (String) actionEvent.getComponent()
                .getAttributes().get("element");

        for (ReturnBody body : returnBodyList) {
            if (!body.getElementName().equals(elementName))
                body.setKeyColumn(false);
            System.out.println("Check ajax: " + body.toString());
        }
    }

您可以在 toggleCheckBox() 方法中实现此目的。

    boolean flag; //Global
    String lastChecked=new String();//global

    if(!flag){
        setFlag(true);
        lastChecked=elementName;
        }

    if(flag){
     for (ReturnBody body : returnBodyList) {
                if (body.getElementName().equals(lastChecked)){
                    body.setKeyColumn(false);
                    lastChecked=elementName;
                    }
            } 
       }