Skip to content Skip to sidebar Skip to footer

Jsf Bean Property Not Evaluated In External Javascript File

If I want to evaluate a JSF bean property from within JavaScript, I see that it works if the JavaScript snippet is inside the xhtml file, but doesn't work when the JavaScript snipp

Solution 1:

Another solution is to change your *.js file to *.xhtml and include it with "<ui:include ... />". To avoid the parser complaining about the use of &, < and > in your *.xhtml file, surround it with a CDATA tag. The disadvantage of this is if the *.js file is being used in other pages, the browser won't be able to cache it.

MyJS.xhtml (changed from MyJS.js)

<xmlversion="1.0"encoding="UTF-8"?><!DOCTYPE html><htmlxmlns="http://www.w3.org/1999/xhtml"xmlns:ui="http://java.sun.com/jsf/facelets"><h:body><ui:composition><scripttype="text/javascript">
//<![CDATA[
  ...your JavaScript code here...
//]]>
</script></ui:composition></h:body></html>

In your index.xhtml file, do the following:

<htmlxmlns="http://www.w3.org/1999/xhtml"xmlns:ui="http://java.sun.com/jsf/facelets">
  ...
<ui:includesrc="MyJS.xhtml" />

Solution 2:

I personally prefer the following approach

<h:inputText id="myHiddenData" value="#{myBean.myProperty}" style="display:none">


$(document).ready(function() {
    alert($("#myHiddenData").val()); // or alert($("#myFormID\\:myHiddenData").val());
});

I just don't like mixing js code with JSF...

Solution 3:

I just was want to check something before answer, like I said in my comment :

I think you can't from external JS, the only way as a workaround you need to pass that value to JS function from JSF page by calling it like functionName(#{value}); and do what you want in JS file like a normal JS value.

Like in your index.xhtml:

<scripttype="text/javascript" >
        $(document).ready(function() {
            functionName('#{myBean.myProperty}');
        });
</script>

or like :

<h:commandLinkaction="..."value="..."onclick="functionName('#{myBean.myProperty}')"/>

and in your js file:

functionfunctionName(var1) {
// DO what you want to do with var1 or varN like normal JS value
}

Sure you can pass a multi-parameters not only single parameter.

Solution 4:

Thanks to the suggestion by @Al-Mothafar, I have finally solved my issue in the following way:

index.xhtml

...
<h:body><scripttype="text/javascript"src="resources/Javascript/jquery/jquery-1.7.2.js" /><scripttype="text/javascript"src="resources/Javascript/MyJS.js" /><scripttype="text/javascript" >var myBeanProperty = '#{myBean.myProperty}';
    </script></h:body>

MyJS.js

$(document).ready(function() {
    alert(myBeanProperty);
});

Post a Comment for "Jsf Bean Property Not Evaluated In External Javascript File"