Show/Hide Panel when checkbox is selected

≡放荡痞女 提交于 2019-12-18 09:37:42

问题


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?


回答1:


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;
}


来源:https://stackoverflow.com/questions/22274026/show-hide-panel-when-checkbox-is-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!