i want to use jQuery to sync values of JSF2 components.
We are using templates. As i am not sure if this may be a cause why the below script is not working, i will show you the code design:
template.xhtml
<h:head>
<script src="#{request.contextPath}/js/my.js" type="text/javascript"></script>
</h:head>
<h:body>
<h:form id="main_form">
<ui:insert name="content"/>
</h:form>
</h:body>
myview.xhtml
<ui:composition ... template="templates.xhtml">
<ui:define name="content">
<p:inputText id="title1" value="#{myBean.title1}" />
<p:inputText id="title2" value="#{myBean.title2}" />
<p:commandLink id="syncBtn" styleClass="ui-icon ui-icon-arrowthick-1-e" />
</ui:define>
my.js
$('#main_form\\:syncBtn').click(function() {
$('#title2').val($('#title1').val());
});
The jQuery scripts/functions are not attached to the elements
I know i can use callbacks (onblur, onclick, etc), but i want to avoid this because and use a more generic solution because i have a lot of those input fields.
EDIT:
i tried BalusC answer (which is of course correct), but there must be another error. because it did not work. I inserted an js alert, but it´s not being dispayed.
$('[id="main_form:syncBtn"]').click(function() {
alert("Test");
});
That’s because they don’t have a client ID of
title1andtitle2, so jQuery can’t find them. They have instead an ID ofmain_form:title1andmain_form:title2. Fix your JS code accordingly.For starters who haven’t memorized how exactly JSF generates HTML, you should ignore the JSF source code when writing jQuery code and instead look at the JSF-generated HTML code. You can do that in the webbrowser by rightclick and View Source or using the "Inspect Element" feature of the webbrowser’s web developer toolset.
See also: