Tom
Tom

Reputation: 67

Show/Hide Panel when checkbox is selected

I'd like to show a panel when a checkbox is selected or hide the same when the checkbox is not selected. Following code works fine when the value of the checkbox changed. However, initially (when building the web page) the panel is always shown. Since the checkbox is deselected the outputLabel ("hallo") should not be displayed. Only after selecting the checkbox, the text should be displayed. So, something goes wrong here...

Here is the code:

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:h="http://java.sun.com/jsf/html">
<h:body>

    <h:form id="myForm">
        <h:selectBooleanCheckbox id="myCheckbox" onclick="hideOrShow(this.checked);"/>
        <h:panelGrid id="myPanel" columns="2" >
            <h:outputLabel for="hallo" value="Halli Hallo" />
        </h:panelGrid>
    </h:form>

</h:body>
<script type="text/javascript">
    function hideOrShow(show) {
        var obj = document.getElementById("myForm:myPanel");
        if (show) {
            obj.style.display = "block";
        } else {
            obj.style.display = "none";
        }
    }
</script>

How to fix this?

Upvotes: 1

Views: 3840

Answers (1)

Vasil Lukach
Vasil Lukach

Reputation: 3728

You don't need javascript for show/hide panel. Here is version of your code with ajax:

 <h:form>
     <h:selectBooleanCheckbox id="myCheckbox" value="#{helloWorld.checked}">
         <f:ajax event="click" render="myPanel" execute="myPanel" />
     </h:selectBooleanCheckbox>
     <h:panelGroup id="myPanel" layout="block">
         <h:outputLabel value="hi there" rendered="#{helloWorld.checked}" />
     </h:panelGroup>
 </h:form>

and bean

private boolean checked;
public boolean isChecked() {
    return checked;
}
public void setChecked(boolean checked) {
    this.checked = checked;
}

Upvotes: 2

Related Questions