Activity › Forums › Salesforce® Discussions › How to show java script variables on a Salesforce Visualforce page?
Tagged: Javascript in Salesforce, Javascript Library, Salesforce Javascript Controller, Salesforce Visualforce Page, Syntax, Visualforce Component
-
How to show java script variables on a Salesforce Visualforce page?
Posted by shariq on July 12, 2017 at 1:07 PMWhat is the syntax of showing it?
Radhakrishna replied 8 years, 9 months ago 2 Members · 3 Replies -
3 Replies
-
Hello Shariq,
Going the one way is difficult. If you need to assign a javascript value to an outputText for example you would need to find the field by it’s ID within the DOM model and use the .value of the element to set the value. I don’t think you’ll see the value change in the form, but when it’s submitting your apex code will get it’s value.
The other way is simpler. To get an apex value in javascript simply do this:
var myVar = ‘{!MyVar}’;
- [adinserter block='9']
-
Hi Radhakrishna,
Can you write the full code with description.
-
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)
Log In to reply.