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) ?

0

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

3 Comments

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 stackoverflow.com/questions/4013410/…
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
Dear BalusC, the server side function is not called, after the event triggered component is disabled. Please advise how to handle the situation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.