i have a form which has a button that submits the form. I need to do something before submits happen. I tried doing onClick on that button but it happens after the submit.
I can't share the code but, generally, what should I do in jQuery or JS to handle this?
55 Answers
If you have a form as such:
<form> ... </form> You can use the following jQuery code to do something before the form is submitted:
$('#myform').submit(function() { // DO STUFF... return true; // return false to cancel form action }); 5Assuming you have a form like this:
<form action="foo.php" method="post"> <input type="text" value="" /> <input type="submit" value="submit form" /> </form> You can attach a onsubmit-event with jQuery like this:
$('#myForm').submit(function() { alert('Handler for .submit() called.'); return false; }); If you return false the form won't be submitted after the function, if you return true or nothing it will submit as usual.
See the jQuery documentation for more info.
0You can use onclick to run some JavaScript or jQuery code before submitting the form like this:
<script type="text/javascript"> beforeSubmit = function(){ if (1 == 1){ //your before submit logic } $("#formid").submit(); } </script> <input type="button" value="Click" onclick="beforeSubmit();" /> 3make sure the submit button is not of type "submit", make it a button. Then use the onclick event to trigger some javascript. There you can do whatever you want before you actually post your data.
2Form:
<form action="/" method="POST" onsubmit="prepareForm()"> <input type="text" value="" /> <input type="submit" value="Submit" /> </form> Javascript file:
function prepareForm(event) { event.preventDefault(); // Do something you need document.getElementById("formId").requestSubmit(); } Note: If you're supporting Safari (which you probably are) you'll need to pull in a polyfill for requestSubmit()