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 snippet is in a separate js file.
So, this works:
index.xhtml
...
<h:body>
<script type="text/javascript" src="resources/Javascript/jquery/jquery-1.7.2.js" />
<script type="text/javascript" >
$(document).ready(function() {
alert('#{myBean.myProperty}');
});
</script>
</h:body>
But this doesn't evaluate the ManagedBean's property:
index.xhtml
...
<h:body>
<script type="text/javascript" src="resources/Javascript/jquery/jquery-1.7.2.js" />
<script type="text/javascript" src="resources/Javascript/MyJS.js" />
</h:body>
MyJS.js
$(document).ready(function() {
alert('#{myBean.myProperty}');
});
In this second case, the alert box contains the not-evaluated string #{myBean.myProperty}
How can I make it work from the external js file?
I personally prefer the following approach
I just don't like mixing js code with JSF...
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:
or like :
and in your js file:
Sure you can pass a multi-parameters not only single parameter.
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)
In your index.xhtml file, do the following:
Thanks to the suggestion by @Al-Mothafar, I have finally solved my issue in the following way:
index.xhtml
MyJS.js