Nacho321
Nacho321

Reputation: 1991

Accessing bean attributes from jquery

Let's say I have a bean with a boolean attribute called display. Is there any way I can access the value of that attribute from jquery? Something like

$(document).ready(function(){ 
    if(bean.display){
       doSomething();
    }
}

Upvotes: 2

Views: 5351

Answers (2)

BalusC
BalusC

Reputation: 1108547

In the context of this question, JSF is merely a HTML/CSS/JS code producer. Just let JSF print a bean property as if it's part of JS code. Just make use EL the usual way.

<h:outputScript>
    $(document).ready(function(){ 
        if(#{bean.display}){
           doSomething();
        }
    }
</h:outputScript>

Open JSF page in webbrowser, rightclick and View Source to see the generated HTML output. It should look something like this:

<script type="text/javascript">
    $(document).ready(function(){ 
        if(true){
           doSomething();
        }
    }
</script>

Note that if JSF did its job of generating the HTML output right, you should not see any Java/JSF/EL code in the HTML output. You just have to write Java/JSF/EL code in such way that it produces exactly the desired HTML/CSS/JS code.


Or, if that script is actually enclosed in a JS file, let JSF print it as a JS variable:

<h:outputScript name="some.js" />
<h:outputScript>var display = #{bean.display};</h:outputScript>

with

$(document).ready(function(){ 
    if(display){
       doSomething();
    }
}

Or, if you absolutely want to keep your initial bean.display JS object syntax, do so:

<h:outputScript name="some.js" />
<h:outputScript>var bean = { display: #{bean.display} };</h:outputScript>

with

$(document).ready(function(){ 
    if(bean.display){
       doSomething();
    }
}

Upvotes: 4

Daniel
Daniel

Reputation: 37051

You also can store it inside some outputText or inputText

For example:

<h:outputText id="my_display" value="#{myBean.display}" style="display:none"/>

and use it like this:

$(document).ready(function(){ 
    if($("#my_display").text() === "someValue"){
       doSomething();
    }
}

Upvotes: 1

Related Questions