0

I have seen both of these being used to update VF page inputs in Javascript dynamically.

Approach 1:

document.getElementById('{!$Component.thePage.theForm.theField}').required = true;

Approach 2:

document.getElementById('thePage:theForm:theField').required = true;

Are there any scenarios that either of them may fail? or better than the other.

2
  • 1
    if you add any element between the hierarchy it will fail Jul 17, 2017 at 4:17
  • Thanks. Would be interested to know which one is recommended and why, or these are just 2 ways to refer it, out of curiosity why would SF introduce referring Component while javascript already got a way to do it. Jul 17, 2017 at 4:23

2 Answers 2

1

Since DOM IDs in Visualforce components are dynamically generated in order to ensure IDs are unique, the advantage of using $Component is this will give you the dynamic order and you dont have to manually create it , in the absolute sense as you have created in Approach 2. So if you have nested tags and in the inner tag you can just reference $Component.idOfElement instead of manually trying to figure out what the ids will be.

In the example below : you can just use {!$Component.theSectionItem} to get j_id0:theForm:thePageBlock:theSection:theSectionItem.

When creating the id for the 'form', VF dynamically named the form id as "j_id0:theForm"

The value for $Component is relative to where you are calling it from. In this scenario its "j_id0:theForm:thePageBlock:theSection".

If you have not broken the chain while referencing the id in getElementById, both approaches will work. Its a mater of convenience what you want to use and how much you want to figure out

<apex:form id="theForm">
    <apex:pageBlock id="thePageBlock" >
        <apex:pageBlockSection id="theSection"> 
             <apex:pageBlockSectionItem id="theSectionItem">
                 <p>The full DOM ID resembles something like this:<br/>
                j_id0:theForm:thePageBlock:theSection:theSectionItem</p>
            </apex:pageBlockSectionItem>
            <apex:outputPanel layout="block" styleClass="clicker"
                onclick="alert('{!$Component.theSectionItem}');">
                First click here
            </apex:outputPanel>
0

Sometimes that kind the code requires maintenance if you add element in the hierarchy.

Better, use getElementbyClassName() approach, instead of getElementById().

<apex:inputField value="{!cust.Name}" styleClass="myElement"/>

Javascript

var form1 = document.getElementById('{!$Component.form1}');
var elements = form1.getElementsByClassName('myElement');

You could loop through the elements and update accordingly.

If there are any elements (table, div etc.) in between form and field, it will not create any issue. Only thing, you need to provide identifiable styleClass name

Also, you can explore document.getElementsByClassName('myElement')

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .