function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
bev90210bev90210 

Very simple JS question

Hi there,
 
I am trying to make a field read-only and would like to do this in the javascript of the page when it loads. I try using the intructions in the VF developer guide with no luck, anyone have an idea? Thanks in advance.
 
Code:
<script>
function atload() 
{

//This line does NOT work
//var ba = document.getElementById('{!$component.sprinknum}');

//This line works, but not very elegant syntax
var ba = document.getElementById("j_id0:j_id3:thePageBlock:j_id53:sprinknum");

ba.readOnly = true;
}
window.onload=atload;

</script>


<*****Valid Visualforce/apex code here>

<apex:inputField id="sprinknum" value="{!Sprinkles__c.Sprinkles_Number__c}"/>  

<*****Valid Visualforce/apex code here>

 
yogesh.rankawatyogesh.rankawat
You should use id for each apex control and then build the id of your control like:

<script>
function atload()
{

//This line does NOT work
//var ba = document.getElementById('{!$component.sprinknum}');

//This line works, but not very elegant syntax
//var ba = document.getElementById("j_id0:j_id3:thePageBlock:j_id53:sprinknum");

//This line works, correctly
var ba = document.getElementById("myPage:myForm:mypageBlock:sprinknum");
ba.readOnly = true;
}
window.onload=atload;

</script>


<*****Valid Visualforce/apex code here>
<apex;page id="myPage">
<apex;form id="myForm">
<apex;pageBlock id="mypageBlock">
<apex;inputField id="sprinknum" value="{!Sprinkles__c.Sprinkles_Number__c}"/>
</apex:pageBlock>
</apex:form>
</apex:page>
<*****Valid Visualforce/apex code here>

:smileyhappy:
dchasmandchasman
You should definitely NOT hard code generated DOM ids like this - salesforce provides $Component to provide the correct level of abstraction from the internals of dom id generation (the details of dom id generation are subject to change at any time!). The usual issues people run into with $Component not resolving to a dom id are because $Component is positional and needs to be located in a place where it can see the component being referenced. Please post the source for your entire page so we can see the use of $Component in context - thanks.
jwetzlerjwetzler
I was going to say exactly what Doug said.  Also is there a reason this needs to be done in javascript? Usually people use an inputField and an outputField bound to the same field, using their rendered attributes to hide/show them based on whatever conditions they have.
bev90210bev90210
Yogesh, you're amazing, that's incredibly clear and well explained. I got it to work just like you explained.
 
Doug and Jill, you two are equally amazing for responding at some ungodly hour, I thought I was the only one who was so excited about VF I can't sleep.
 
Forward march!