+ Start a Discussion
Aditya Rayavarapu 5Aditya Rayavarapu 5 

Javascript in VF

Hello,
I have an output field in a VF page. When the page is loaded, if the output field is empty, then javascript must output a text value of "Anonymous". I can get the output to generate when the page is loaded, but it is not considering whether the output field is null or not. I tried using ".value" at the end of var x, but it doesn't work. Any help? Thanks

<apex:outputfield id="first" value="{!c.FirstName__c}"/>
           
            <output id="firstname"></output>

<script>
 
  var x = document.getElementById('{!$Component.first}');
 
window.onload = function(){
     
if ( x !== undefined ) {
   document.getElementById('firstname').value="Anonymous";
     
}
   }
</script>
Suresh RaghuramSuresh Raghuram
I suspect that you are not getting the x value in script.
do a check after the var x= document.getElementById('{!$Component.first}');
write an alert statement after the above line of code alert(x).
And also go through this link
https://www.salesforce.com/us/developer/docs/pages/Content/pages_variables_global_component.htm
Aditya Rayavarapu 5Aditya Rayavarapu 5
Hi, I tried that, and I get the alert as null, even when there is a value is x. However, I suspect that the alert is shooting off before the body of the window loads. 
Suresh RaghuramSuresh Raghuram
Then place the alert in window.onload method.
Aditya Rayavarapu 5Aditya Rayavarapu 5
Hi, I have tried that as well, and am still getting the alert. It is always reading the outputfield value as null, even when there is a value in it.