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
MellowRenMellowRen 

How to get OutputText value (URL) into JavaScript

Hi

 

Can anyone help with this? I have what is a pretty simple (for the moment) visualforce page:

 

<apex:page StandardController="Opportunity">

    <apex:outputText id="myURLx" value="https://cs2.salesforce.com/home/home.jsp" />
    
    <script type="text/javascript">
        var a = document.getElementById('{!$Component.myURLx}');
        alert(a);
    </script>

    <!-- Rest of Visualforce page, just shows the Opportunity ID and Name -->

</apex:page>

 

My expectation is that the alert should show a message that says "https://cs2.salesforce.com/home/home.jsp" but rather I get "[object HTMLSpanElement]". I have found that replacing the URL in the value attribute with "hello" produces the same result. The OutputText itself is displaying the expect value on the rendered page. I have tried changing the definition of 'a' to these:

 

var a = document.getElementById('{!$Component.myURLx}').value;
var a = document.getElementById('{!$Component.myURLx}').text;
var a = document.getElementById('{!$Component.myURLx}').html;
var a = document.getElementById('{!$Component.myURLx}').string;
var a = document.getElementById('{!$Component.myURLx}').asString;

 

But the alert then just states "undefined". I tried using Apex:Variable instead of OutputText but the javascript refused to run.

 

My Google searches seem to suggest the above *should* work. I am really hoping that I have just made a silly error that is eluding my strained brain.

 

Any ideas?

 

Regards

MellowRen

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

Use the innerHTML property - that will give you the contents of the span:

 

<script type="text/javascript">
   var a = document.getElementById('{!$Component.myURLx}').innerHTML;
   alert(a);
</script>

 

All Answers

bob_buzzardbob_buzzard

Use the innerHTML property - that will give you the contents of the span:

 

<script type="text/javascript">
   var a = document.getElementById('{!$Component.myURLx}').innerHTML;
   alert(a);
</script>

 

This was selected as the best answer
MellowRenMellowRen

Ha ha ha ha. I can't believe how close I got. Works perfectly, thank you.