Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle line breaks from backing bean in JavaScript

I'm trying to use a string from my backing bean which may contain line breaks as a parameter for my JavaScript method:

Snippet from xhtml:

<a4j:commandLink id="showEntry"
    immediate="true"
    styleClass="smallSpaceLeft"
    action="#{bean1.method()}"
    onclick="jsMethod('#{entry.text}')"
    value="#{messages['general.click']}" />

Everything works fine, except the string contains any line breaks. E.g.: #{entry.text} = "First line.\nSecond line."

The html-output looks like:

<a class="smallSpaceLeft" href="#" id="j_id279:0:showEntry"
    name="j_id279:0:showEntry" onclick="jsMethod('First line.
    Second line.');A4J.AJAX.Submit('j_id272',event,
    {'similarityGroupingId':'j_id279:0:showEntry','parameters':  
    {'j_id279:0:showEntry':'j_id279:0:showEntry'} } );return false;">Click me</a>

So the JavaScript is broken as a line break ends a command. How can I avoid this?

like image 691
ottel142 Avatar asked Jun 17 '26 00:06

ottel142


1 Answers

You cannot handle it in javascript, you must replace the linebreaks before you print the code.

In strings you may prepend a backslash before the linebreak. But as there may be more questionable characters I would prefer to URL-encode the string and then decode it in javascript by using decodeURIComponent() .

like image 185
Dr.Molle Avatar answered Jun 18 '26 14:06

Dr.Molle