Hello Shariq,
Displaying a JavaScript variable can be done, but not as easily as you might think, as you can’t embed ‘<‘ characters in the output string.
I use the following mechanism:
Two methods in my controller to generate the beginning/end of the JavaScript write:
public String getJSStart() { return ‘<script>document.write(‘; } public String getJSEnd() { return ‘)</script>’; }
I can then do the following on my page:
<script> var str=”Hello world!”; </script> <apex:outputText value=”{!JSStart}str{!JSEnd}” escape=”false”/>
and I get the output I expect. Make sure you set the escape=”false” attribute, otherwise you will just see a text version of the JavaScript.
Setting a value is a little easier, although you still have to work a bit to get the component’s id. Here’s an example:
var reasonEle=document.getElementById(‘{!$Component.dcForm.dcBlock.dcSection.reasonItem.reason}’); var str=’Hello world’; if (reasonEle.value.length==0) { reasonEle.value=str; }
When getting the element by ID, you have to supply the full path through the VisualForce component hierarchy. In my example above, the element (id=reason) is within a PageBlockSectionItem (id=reasonItem) within a PageBlockSection (id=dcSection) within a pageblock (id=dcBlock) within a form (id=dcForm)