0

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");
});
jimmybondy
  • 2,092
  • 3
  • 21
  • 33
  • you can keep em sync all in "real time" with onkeyup , like this http://stackoverflow.com/a/10981475/617373 – Daniel Jun 25 '12 at 07:55
  • Thanks Daniel. But i want to give the user more control and let him decide to copy the values from one field to another. – jimmybondy Jun 25 '12 at 09:14

1 Answers1

4

That's because they don't have a client ID of title1 and title2, so jQuery can't find them. They have instead an ID of main_form:title1 and main_form:title2. Fix your JS code accordingly.

$('#main_form\\:syncBtn').click(function() {
    $('#main_form\\:title2').val($('#main_form\\:title1').val());
});

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:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555