How can I know the id of a JSF component so I can use in Javascript

前端 未结 6 1340
北海茫月
北海茫月 2020-11-22 02:47

Problem: Sometimes you will want to access a component from javascript with getElementById, but id\'s are generated dynamically in JSF, so you

6条回答
  •  醉酒成梦
    2020-11-22 03:33

    Answer: So this is the technique I'm happiest with. Doesn't require doing too much weird stuff to figure out the id of a component. Remember the whole point of this is so you can know the id of a component from anywhere on your page, not just from the actual component itself. This is key. I press a button, launch javascript function, and it should be able to access any other component, not just the one that launched it.

    This solution doesn't require any 'right-click' and see what the id is. That type of solution is brittle, as the id is dynamically generated and if I change the page I'll have to go through that nonsense each time.

    1. Bind the component to a backing bean.

    2. Reference the bound component wherever you want.

    So here is a sample of how that can be done.

    Assumptions: I have an *.xhtml page (could be *.jsp) and I have defined a backing bean. I'm also using JSF 2.0.

    *.xhtml page

    
    
    
    
    

    BackBean.java

    UIInput emailAddyInputText;
    

    Make sure to create your getter/setter for this property too.

提交回复
热议问题