+ Start a Discussion
SexmanSexman 

I don't know how to use the "$component" global variable :'(

I need to use it in order to make a javascript function work. Here I paste the entire visualforce page (don't worry, it's small): 

 

 

<apex:page >
    
    <apex:form id="morning">
    
    <apex:commandButton onclick="beforeTextSave();" value="Button" reRender="msgpost"/>
    <apex:outputText id="msgpost"/>
    
  
    
    </apex:form>
  
    <script>
        function beforeTextSave() {
            document.getElementById('{!$component.morning.msgpost}').value = 'Hello World';
        }
    </script>
    
</apex:page

 

 

It's supposed when I press the button, a message ("Hello World") should appear in the screen. But for some reason I can't make it work :'(

 

Do you know what is wrong in my code?

 

 

Cheers.

Best Answer chosen by Admin (Salesforce Developers) 
SSRS2SSRS2

See following sample code.hope this help..Use 'innerHTML' to get and set output text value.

 

<apex:page >
<apex:form id="morning">
<apex:commandButton onclick="return beforeTextSave();" value="Button" />
<apex:outputText id="msgpost" />
</apex:form>
<script>
function beforeTextSave() {
document.getElementById('{!$component.morning.msgpost}').innerHTML = 'Hello World';
//alert('2'+document.getElementById('{!$component.morning.msgpost}').innerHTML);
return false;
}
</script>
</apex:page>

  -Suresh

 

All Answers

aballardaballard

You need to use it within the scope of the component it accesses.   Try putting it before the </apex:form> tag. 

 

Personally, I would probably add a parameter to the function and use it directly at the point of the action; e.g.

 

<apex:commandButton onclick="beforeTextSave({!$Component.msgpost});" value="Button" reRender="msgpost"/>

 

then you can put the script (modified to expect the parameter) anywhere you want to. 

<apex:commandButton onclick="beforeTextSave();" value="Button" reRender="msgpost"/>
SSRS2SSRS2

See following sample code.hope this help..Use 'innerHTML' to get and set output text value.

 

<apex:page >
<apex:form id="morning">
<apex:commandButton onclick="return beforeTextSave();" value="Button" />
<apex:outputText id="msgpost" />
</apex:form>
<script>
function beforeTextSave() {
document.getElementById('{!$component.morning.msgpost}').innerHTML = 'Hello World';
//alert('2'+document.getElementById('{!$component.morning.msgpost}').innerHTML);
return false;
}
</script>
</apex:page>

  -Suresh

 

This was selected as the best answer
SexmanSexman

Thanks, aballard! ;)