CF_HoneyBadger
CF_HoneyBadger

Reputation: 3009

Using ColdFusion variable with line breaks in JavaScript

I have a text area that accepts line breaks. The content of that text area is saved in a coldfusion variable (lets call it #fieldVal#). So, my variable contents look like

textline 1
textline 2

Later on, I use that variable in JavaScript

document.all.fieldName.value = "#fieldVal#";

However, when the JavaScript hits the page, it looks like this:

document.all.fieldName.value = "textline 1
textline 2";

and the script breaks because the first line doesn't end in a semicolon.

I tried setting a JavaScript variable to the ColdFusion text then doing a replace(), but I still hit the same issue with the line not ending correctly.

I think I'm missing something obvious but I am just not seeing it. Can someone tell me what I'm missing here?

Upvotes: 1

Views: 592

Answers (3)

Brad Wood
Brad Wood

Reputation: 3953

Use the JSStringFormat() function. It is designed to escape meta characters in JavaScript

Escapes special JavaScript characters, such as single-quotation mark, double-quotation mark, and newline.

https://wikidocs.adobe.com/wiki/display/coldfusionen/JSStringFormat

document.all.fieldName.value = "#JSStringFormat( fieldVal )#";

If you're using ColdFusion 10+ or Lucee Server, use EncodeForJavaScript().

https://wikidocs.adobe.com/wiki/display/coldfusionen/EncodeForJavaScript

Upvotes: 14

CF_HoneyBadger
CF_HoneyBadger

Reputation: 3009

I stumbled upon a code snippet that worked. Its a bit...convoluted, but it works.

document.all.fieldName.value = "#Replace(Replace(URLDecode(Replace(Replace(URLEncodedFormat(fieldVal), "%0D", " ", "ALL"), "%0A", "", "ALL")),CHR(34),"", "ALL"),CHR(39),"", "ALL")#"

Upvotes: -1

rrk
rrk

Reputation: 15846

Option 1

document.all.fieldName.value = "#Replace(trim(fieldVal), chr(10) & chr(13), ' ', 'ALL')#"; 

Option 2 (Possible that the same issue occur in this too.)

Try using ToScript()

ToScript(fieldVal, valueVar)

Toscript initializes a variable with the coldfusion variable value and you can use like any JS global variable.

document.all.fieldName.value = valueVar;

Option 3 (If you need in HTML form)

Use coldfusion function ParagraphFormat() which changes line breaks into <br/>.

Upvotes: 1

Related Questions