2

I am trying to create a tabpanel and calling a javascript function with its onclick event. How do I pass the name of the selected tab to a javascript function every time a tab is clicked?

Something like:

<apex:tabPanel switchType="client" selectedTab="Tab1" onclick="javascript:myFunction(this.selectedTab)" //something like this
     <apex:tab label="Tab1" name="Tab1" id="Tab1"> Tab1 </apex:tab>
     <apex:tab label="Tab2" name="Tab2" id="Tab2"> Tab2 </apex:tab>
</apex:tabPanel> 

<script type="text/javascript">
     function myFunction(tabName)
     {
        if(tabName == 'Tab1')
           do something...
         if(tabName == 'Tab2')
           do something...
     }
</script>

onclick="javascript:myFunction(this.selectedTab)" does not work .... How can I achieve this please ??

2

When using the switchType="client" the tabPanel data is already rendered to the browser so it looks like the best event that you can hook to for detecting a tab switch is the ontabenter event on the tab itself. The oncomplete event is only fired on an ajax switchType to notify you that the ajax request & response process is finished, so that event isn't applicable here.

Salesforce <apex:tab /> Documentation

You can pass the DOM Id of the tab as a parameter to your function using the $Component.yourComponentId syntax. The DOM Id which is rendered is the tab body, not the label (shown as a tab) though it is trivial to get a reference to the tab as shown below.

<script>
    function tabSwitchHandler(elementId) {
        console.log('Tab body DOM Id: ' + elementId);

        // the tab is the body DOM id suffixed by _lbl
        var tabId = elementId + '_lbl';

        // get the tab itself
        var tabLabelElement = document.getElementById(tabId);

        // get the body
        var tabBodyElement = document.getElementById(elementId);

        console.log(tabLabelElement);
        console.log(tabBodyElement);
    }
</script>

<apex:tabPanel switchType="client" selectedTab="name2" id="theTabPanel">
    <apex:tab label="One" name="name1" id="tabOne" ontabenter="tabSwitchHandler('{!$Component.tabOne}');">content for tab one</apex:tab>
    <apex:tab label="Two" name="name2" id="tabTwo" ontabenter="tabSwitchHandler('{!$Component.tabTwo}');">content for tab two</apex:tab>
</apex:tabPanel> 
| improve this answer | |

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.