1

I have an onclick event that depends on the state of a variable. So I need to do something like

onclick="#{object.isEnabled ? 'ch.my.js_method('#{object.property}'); return false;' : 'return false;'"

The problem is, that I can't use ' inside of the onclick. How can I escape the quotes inside of the EL?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Are there any errors in the console? – VC1 Oct 08 '15 at 15:16
  • The question is sound, but you're using curly quotes instead of straight quotes. Is this also the case in real code? This only introduces a red herring in the question. Look closer at the code you just posted yourself here above. The difference between `‘` and `'` is pretty clear. Those double quotes around the attribute value are even invalid because those are curly instead of straight. Code usually only accepts straight quotes. – BalusC Oct 08 '15 at 15:18
  • This is just an error in typing: in the source file I used straight quotes. However, it did not work... – Katja Gräfenhain Oct 08 '15 at 15:23
  • Nope, no console errors but an error when parsing the xhtml – Katja Gräfenhain Oct 08 '15 at 15:27

2 Answers2

4

You can escape them with \ or \\, but rules differ per EL implementation, because it isn't clear cut in EL spec (Oracle's EL impl needs single backslash, but Apache needs double backslash). And you need the += operator to string-concatenate the EL expression.

<x:someComponent onclick="#{object.isEnabled ? 'ch.my.js_method(\'' += object.property += '\'); return false;' : 'return false;'}" />

Safest bet is to just create an alias with help of <c:set>.

E.g.

<c:set var="js_method" value="ch.my.js_method('#{object.property}'); return false;" />
<x:someComponent onclick="#{object.isEnabled ? js_method : 'return false;'}" />

You've only still a potential problem if #{object.property} can contain JS-special characters which can in turn cause invalid JS output, such as single quotes or newlines. Head to the second link below for the solution to that.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • The escaping did not work. Error: `ReferenceError: invalid assignment left-hand side` – Katja Gräfenhain Oct 14 '15 at 15:04
  • Neither did the version with the alias. `SyntaxError: missing : in conditional expression ...ch.my.js_method('343556'); return false; : 'return false;` looks like the quotes around the onclick event are missing... – Katja Gräfenhain Oct 14 '15 at 15:07
  • I just forgot a `}`. Answer has been fixed. Sorry for that. Just blame Stack Overflow for not having a compiler and syntax checker built into the message editor :) – BalusC Oct 14 '15 at 15:12
1

I found another solution: just invert the condition and add the event afterwards. This way the quotes around the JS method are not needed:

onclick="#{object.isEnabled == 'false' ? 'return false;' : ''} ch.my.js_method('#{object.property}'); return false;"