0
<form id="formReg" action="reg.php" method="post">
. . . 
<button id="sub">Register</button>
</form>

This works, but I want to place button #sub outside the form tag, and run the form processing using jquery:

$("#sub").click( function() {
    $.post( $("#formReg").attr("action")),
    $("#formReg :input").serializeArray();      
});

It doesn't work. Is it possible at all ?

1
  • Thanks to everyOne. I need time to study and try all these solutions. Commented Jan 12, 2013 at 17:49

4 Answers 4

1

Well, it probably doesn't work because the form submission cancels the calling of any further event listeners. You should do form processing like this:

$("#formReg").on('submit', function() {
    // process form
    // You can even stop the form submission here,
    // just return 'false' and it will stop.
    // That's very useful for form validation etc.
});

If you need that button to submit the form, you could do this:

$("#sub").on('click', function() {
    $("#sub").submit(); // This will submit the form AND call the event listener. Nice, eh?
});

That should work whereever the button is on the page.

EDIT:
Thanks, fibreFoX, for remembering me of the deprecation of .click() and .submit()!

EDIT 2:
Musa is right, you used $.post() incorrectly. But I don't know if the AJAX request actually completes if the user gets thrown of the page by the form submission. If you don't want the user to go to the page the form is submitted to, you should return false from the submit listener.

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

Comments

1

why dont u place the button outside (as you said) and call just this:

$("#formReg").submit();

btw: you should use this to bind events

$("#sub").on("click", function(){
... your code ...
});

Comments

1

If you are trying to post your form via ajax you used $.post incorrectly

$("#sub").click( function() {
    $.post($("#formReg").attr("action"), $("#formReg").serialize());    
});

Comments

1

Try this

$("#sub").click( function() {
    $.post( $("#formReg").attr("action"), $("#formReg").serialize());
});

Note I have remove the semi-colon after the serialize method and am calling serialize() on the form element. This is if you want to do it using Ajax.

If you just want to submit the form, use this

$("#sub").click( function() {
    $("#formReg").submit();      
});

Comments

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.