Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
806 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...