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?
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?
- Are there any errors in the console? – VC1 Commented Oct 8, 2015 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 Commented Oct 8, 2015 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 Commented Oct 8, 2015 at 15:23
- Nope, no console errors but an error when parsing the xhtml – Katja Gräfenhain Commented Oct 8, 2015 at 15:27
2 Answers
Reset to default 5You 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:
- How to concatenate Strings in EL expression?
- How do I pass JSF managed bean properties to a JavaScript function?
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;"