Getting JSF-defined component with Javascript

微笑、不失礼 提交于 2019-12-08 04:13:03

问题


I'm creating an interface using JSF, and I'd like the value of one text field to provide the default for a second if the second hasn't yet been set. The crucial code will look something like this:

<h:outputScript>
function suggestValue2() {
    var value2 = document.getElementById('value2').value;
    if (value2 == "") {
        document.getElementById('value2').value = document.getElementById('value1').value;
    }
}
</h:outputScript>

<h:inputText
    id="value1"
    onblur="suggestValue2();" />

<h:inputText
    id="value2" />

The problem is this doesn't actually work. The actual IDs of those two input elements get prefixed with some JSF-generated values, which tanks the getElementById calls. What's the best way for me to accomplish what I'm trying to accomplish here?


Edit: I should note that this is going to appear inside a composite component, which could wind up appearing multiple times on a single page. JSF dynamically setting the actual ID represents desired behavior.

回答1:


Bind the component to the view,

<h:inputText binding="#{input1}" ... />

so that you can just print its client ID elsewhere in the view by UIComponent#getClientId().

<h:outputScript>
    var input1 = document.getElementById('#{input1.clientId}');
    // ...
</h:outputScript>

As you mentioned that you're inside a composite component, it may be good to know that composite component's own client ID is already available via #{cc.clientId}. So the more recommended alternative would be:

<cc:implementation>
    <h:outputScript>
        var input1 = document.getElementById('#{cc.clientId}:input1');
        // ...
    </h:outputScript>
    ...
    <h:inputText id="input1" ... />
    ...
</cc:implementation>

See also:

  • Integrate JavaScript in JSF composite component, the clean way



回答2:


Jsf uses a concept "naming containers" which says the id need not be unique within a provided container. Provided the container has an Id. So if you are not giving an Id to the container jsf appends the unpredictable values before the element. With id for container it becomes containerid:elements id. And this can be used in JavaScript reliably



来源:https://stackoverflow.com/questions/14402601/getting-jsf-defined-component-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!