Nacho321
Nacho321

Reputation: 1991

Pull bean value as String for Javascript use

I'm trying to set a component's text based on a bean's value. I'm using jquery for this because the text changes depending on certain conditions.

So, the jquery code looks like this:

window.onload =function(){
    $('.pnx-inline-input').on("change keyup paste", function(){
        var saveText = #{extra.Active_Save};                
        $('.save-button .pnx-btn-text').html(saveText);
});

The Extra bean handles the localization. So, let's say that the locale is France, and the text is Enregister. The thing is that when rendered the page, the code segment looks like this

window.onload =function(){
    $('.pnx-inline-input').on("change keyup paste", function(){
        var saveText = Enregister;              
        $('.save-button .pnx-btn-text').html(saveText);
});

Of course, Enregister is not defined anywhere, and this causes an error. I need to have to code look like

var saveText = "Enregister";

for this to make sense.

How can I make this happen? Thanks!

Upvotes: 2

Views: 861

Answers (1)

BalusC
BalusC

Reputation: 1108557

JSF is in the context of this question merely a HTML code generator. Just write down those quotes yourself in the HTML template. They are part of generated HTML output, not of the Java variable. You know, JavaScript doesn't run together with Java/JSF (i.e. it's not server side). Instead, it runs together with HTML (i.e. it's client side).

var saveText = "#{extra.Active_Save}";

Note that you still need to take into account that the value is properly JS-escaped, otherwise the whole thing would still break in JavaScript side if the string itself contains doublequotes or other special characters in JS such as newlines. The JSF utility library OmniFaces has an EL function for the very purpose, the #{of:escapeJS()}:

var saveText = "#{of:escapeJS(extra.Active_Save)}";

You can of course also homegrow your own based on e.g. Apache Commons Lang StringEscapeUtils.

Upvotes: 5

Related Questions