1
<script>
function toggleContacts(className){
    elem = document.getElementsByClassName(className)[0];
    if(elem.style.display == 'none')
        elem.style.display = 'block';
    else
        elem.style.display = 'none';
}
</script>

<apex:form >

    <apex:repeat value="{!accs}" var="a">

        <apex:pageBlock title="{!a.Name}">
            <apex:pageBlockButtons location="top">
                <input type="button" onclick="toggleContacts('tbl-{!a.id}');" value="Show/Hide contacts" class="btn" /> 
            </apex:pageBlockButtons>
            <apex:pageBlockSection >
                <apex:outputField value="{!a.Phone}"/>
            </apex:pageBlockSection>

            <apex:outputPanel styleClass="tbl-{!a.id}" style="display:none;">
            <apex:pageBlockTable value="{!a.Contacts}" var="c">
                <apex:facet name="header">Contacts</apex:facet>
                <apex:column value="{!c.Name}"/>
            </apex:pageBlockTable>
            </apex:outputPanel>
        </apex:pageBlock>

    </apex:repeat>

</apex:form>
2

The JS function toggleContacts() accepts className as argument. It then searches the DOM for the element with the specified class (e.g. if a function is called with argument "green-panel", like so: toggleContacts("green-panel"), the function will browse the DOM for element with class="green-panel"), examines whether the retrieved element is visible or hidden on the page and switches it's visibility accordingly (if it was previously visible, after the call it will be hidden, and vice versa).

The outputPanel in the repeat block is marked with class comprised of prefix "tbl-" and postfix of and Id of the record currently being rendered. In practice, this will result in HTML output resembling something like:

<div class="tbl-001g000000ABVGd" style="display:none;">
...
</div>


The button within the same repeat block calls aforementioned JS function with the argument same as the css class name built for the output panel, for the purpose of JS function being able to identify and find the targeted HTML element and change it's visibility.

  • Thank you for giving me such a good description. And what does it mean 'elem = document.getElementsByClassName(className)[0]; ' – RaJu Jan 15 '14 at 14:13
  • 1
    With document.getElementsByClassName(...) you can access page elements per class name. With [0] only the fist element with given class name will be taken. Read more about HTML DOM Elements – Sergej Utko Jan 15 '14 at 14:17
  • 1
    "elem" is just a variable, could be even defined as a local (within the scope of the function) to avoid confusion... look at it like: var elem = document.getElementsByClassName(className)[0] – dino ursic Jan 15 '14 at 14:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.