1

I can submit my JSF generated form with this code :

<h:commandButton  id="btnValidate" type="submit"  value="#{rb.REGISTER}" action="#{login.registerAccount}" />

but I want to process JS code before submitting my form so I added onClick="test();" with commandButton type to button :

<h:commandButton  id="btnValidate" type="button"  value="#{rb.REGISTER}" action="#{login.registerAccount}" onClick="test();" />

My test function :

function test(){    
   $('#j_idt14\\:register_form').submit();

}

With this code, my form is submitted but my login.registerAccount function is no longer called.

How to submit a form with JS and call server side function (attribute action) ?

Olivier J.
  • 3,115
  • 11
  • 48
  • 71

1 Answers1

4

You don't need to submit the form by JS yourself. It would only disturb JSF own job of handling the form submit. The onclick merely offers you a hook to execute some JavaScript code before the form is submitted. The form will always be submitted unless you return false from inside the onclick handler.

So, if you're not interested in blocking the form submit and just always want to submit it, just remove the submit() call.

E.g.

<h:commandButton ... onclick="onbeforesubmit()" />

with

function onbeforesubmit() {
    // ...
}

Or if you're actually interested in blocking the form submit depending on the logic in the handler, then return true or false accordingly. Returning false will block the form submit.

E.g.

<h:commandButton ... onclick="return validate(this.form)" />

with

function validate(form) {
    var valid = true;

    // ... (some logic which may set it to false)

    return valid;
}

(note that I have demonstrated an easier way to get the parent form inside the function than using $('#j_idt14\\:register_form'); you just have to do $(form) to wrap it in a jQuery object if necessary)

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • You're welcome. Note that client side validation is not robust and you should never let your business code rely on it. Make use of server side (JSF) validation if possible. They can easily be ajaxified with onchange/onblur. See also among others http://stackoverflow.com/questions/4013410/jsf2-validation-clientside-or-serverside – BalusC Dec 18 '12 at 13:56
  • I do both, I ensure with JS that all fields are just filled and JSF do after the "busy work" of validation and add or not `FacesMessages`. Thank you again – Olivier J. Dec 18 '12 at 14:00
  • Dear BalusC, the server side function is not called, after the event triggered component is disabled. Please advise how to handle the situation. – AVA Sep 11 '13 at 11:30