0

Problem: Javascript single quotes from CF variable

ColdFusion
On the DFWCFUG list someone asked if anyone had a solution regarding a problem with passing a ColdFusion variable into an agument of a Javascript call when single quotes might exist in the variable, causing the function call to barf.

Someone suggested replacing all single quotes with double quotes.  This however might not be optimal if you are dealing with someone's name like Conan O"Brian, of if the text was Don"t do this.   I suggested doing the following to avoid this problem.  Assume the following code:

<cfoutput>
onclick="doIt('#ourColdFusionString#');"
</cfoutput>

If you wanted to make that same function call safe from single quotes, you could do this:

<cfoutput> onclick="doIt('#replace(ourColdFusionString,"'","\'","all")#');" </cfoutput>

Of course in most cases, it would make more sense to create a user defined function to manage this so you don't have to continually type the same replace code. Additionally, it would easily allow you to change the rules for what might be safe for your Javascript function.
tags:
ColdFusion

Search