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) ?
You don’t need to submit the form by JS yourself. It would only disturb JSF own job of handling the form submit. The
onclickmerely offers you a hook to execute some JavaScript code before the form is submitted. The form will always be submitted unless you returnfalsefrom inside theonclickhandler.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.
with
Or if you’re actually interested in blocking the form submit depending on the logic in the handler, then return
trueorfalseaccordingly. Returningfalsewill block the form submit.E.g.
with
(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)