iRomul
iRomul

Reputation: 351

Change value of checkbox using ajax in JSF

I try to solve the following problem: i have a group of h:selectBooleanCheckbox that generates using ui:repeat:

<h:form>

    <ui:repeat value="#{uiCheckboxList.list}" var="boxElement" varStatus="i">

        <h:selectBooleanCheckbox id="a">

            <f:attribute name="value" value="#{boxElement.enabled}"/>

        </h:selectBooleanCheckbox>
        <h:outputLabel value="#{boxElement.val}" for="a"/>

    </ui:repeat>

</h:form>

Values and label's text stored in array list and controls by servlet:

@ManagedBean(name="uiCheckboxList")
@ApplicationScoped
public class CheckBoxListBean implements Serializable {

private ArrayList<BoxTuple> list;
// BoxTyple is class with 2 fields - val (double) and enabled (boolean)

public CheckBoxListBean() {

    list = new ArrayList<>();

    for(double i = -2.0; i <= 2.0; i += 0.5) {
        list.add(new BoxTuple(i, false));
    }
    // Set first element to true
    list.get(0).setEnabled(true);

}

public ArrayList<BoxTuple> getList() {
    return list;
}

public void setList(ArrayList<BoxTuple> list) {
    this.list = list;
}

And my problem is this: when you click on one of the h:selectBooleanCheckbox server asynchronously sent request with information about the changed box, and then change the values of the another boxes without reloading page. In other words, I need to get the behavior of radio boxes. Maybe it sounds silly, but I need to solve this problem. How can i implement this?

Upvotes: 1

Views: 2969

Answers (1)

Zim
Zim

Reputation: 1483

You can do something like this:

<h:form id="form">
    <ui:repeat value="#{uiCheckboxList.list}" var="boxElement"
        varStatus="i">
        <h:selectBooleanCheckbox id="a">
            <f:attribute name="value" value="#{boxElement.enabled}" />
            <f:ajax render="form"
                listener="#{uiCheckboxList.listen(boxElement)}" />
        </h:selectBooleanCheckbox>
        <h:outputLabel value="#{boxElement.val}" for="a" />
    </ui:repeat>
</h:form>

(get rid of the varStatus if you don't use it)

public void listen(BoxTuple tuple) {
    if (tuple.enabled)
        for (BoxTuple t : list)
            if (!t.equals(tuple))
                t.setEnabled(false);
}

Upvotes: 1

Related Questions