Header

Tuesday, October 25, 2011

Visualforce Component IDs in JQuery

I bet most of you are using css classes in your vf components in order to select them using JQuery. I believe this the easiest workaround but not really that efficient especially if you have a number of vf components in your page and most of them should be using similar css classes. You are not able to use JQuery with the vf component's ID since it adds additional data to the ID you specified. The additional data denotes the component's position in the vf page structure. There is an easy way to refer to your vf components IDs without doing much code, however, just make sure that you don't have duplicate IDs or else this approach will fail. You may refer to your specific visualforce component by using this JQuery expression: $('[id$=YourVFComponentID]'). This will search all the IDs of the page components which contains the specified text after the id$.

Here's an example:

<apex:page>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<script>
    $(function()
    {
        $('[id$=itDate]').datepicker();  
    });
</script>

    <apex:form >
        <apex:pageblock>
            <apex:pageBlockSection columns="2">
                <apex:pageBlockSectionItem >
                    <apex:outputlabel value="Date:"/>
                    <apex:inputText id="itDate"/>
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>
        </apex:pageblock>
    </apex:form>

</apex:page>     

No comments:

Post a Comment