Activity Forums Salesforce® Discussions How to show java script variables on a Salesforce Visualforce page?

  • Radhakrishna

    Member
    July 13, 2017 at 5:09 am

    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}';

  • shariq

    Member
    July 14, 2017 at 2:03 pm

    Hi Radhakrishna,

    Can you write the full code with description.

  • Radhakrishna

    Member
    August 1, 2017 at 11:14 am

    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.

Popular Salesforce Blogs

Popular Salesforce Videos