Ben Pelletier
Ben Pelletier

Reputation: 33

How to output variables dynamically in ColdFusion

I am trying to replace a value with a passed value using javascript or coldfusion. The idea is we have a template which outputs values in the grid. But the values displayed need be dynamically determined by a query. So far I haven't been able to come up with any good ideas.

Here is a sample of something I thought would of work (but does not). It may explain what I am trying to do:

<cfset StaticValue="DynamicValue">

<cfset DynamicValue="What I Want To Show">

<script type="text/javascript">
   document.getElementById("demo").innerHTML="<cfoutput>#StaticValue#</cfoutput>";
</script>

<cfoutput>#<span id="demo"></span>#</cfoutput>

Upvotes: 1

Views: 8792

Answers (3)

Merle_the_Pearl
Merle_the_Pearl

Reputation: 1521

Are you trying to compare if they are the same and then display it if they are?

<cfset StaticValue="DynamicValue"> 

<cfif staticvalue is dynamicvalue>
   <cfset DynamicValue="What I Want To Show"> 

   <script type="text/javascript">
   <cfoutput>
   document.getElementById("demo").innerHTML="#DynamicValue#"; 
   </cfoutput>
   </script> 
</cfif>

Not sure what u are trying to do here - as this will error on bad variable inside your # #

<cfoutput>#<span id="demo"></span>#</cfoutput> 

Should be:

<cfoutput>
<span id="demo">
#dynamicvalue#
</span>
</cfoutput> 

If you are just trying to get a url to display:

<cfoutput>
<span id="demo">
<a href="#dynamicvalue#">#dynamicvalue#</a>
</span>
</cfoutput> 

Upvotes: 0

Peter Boughton
Peter Boughton

Reputation: 112160

To use an existing string/variable as a variable name, you need to use bracket notation.

In CF, if you haven't explicitly scoped a variable, it is created in the Variables scope, so you can do:

<cfset StaticValue="DynamicValue">

<cfset DynamicValue="What I Want To Show">

<!--- outputs value of Variables.DynamicValue --->
<cfoutput>#Variables[StaticValue]#</cfoutupt>

(This works will all scopes/structs/queries/etc)

NOTE: If the variable is to be output inside of a JavaScript string, you need to wrap it in JsStringFormat(...) to ensure the appropriate characters are escaped.

Upvotes: 4

Evik James
Evik James

Reputation: 10483

First of all, this is wrong:

<cfoutput>#<span id="demo"></span>#</cfoutput>

You are suggesting that there is a CF variable named

<span id="demo"></span>

Your question isn't clear, so neither can be my answer, but I suspect that you are trying to do this:

<script type="text/javascript">
    <cfoutput>
        document.getElementById("demo").innerHTML="#StaticValue#";
    </cfoutput>
</script>

<span id="demo"></span>

When this JavaScript runs on the page, the string "DynamicValue" will be written into the span#demo.

Upvotes: 2

Related Questions