Change form data before submitting

I use jQuery in combination with a form plugin and I would like to intercept the form data before submitting and make changes.

The form plugin has a property called beforeSubmit that should do this, but I seem to be having trouble getting the function I will specify to run.

Here's the markup for the form (some style details are omitted):

<form id="form1"> <fieldset id="login"> <legend>Please Log In</legend> <label for="txtLogin">Login</label> <input id="txtLogin" type="text" /> <label for="txtPassword">Password</label> <input id="txtPassword" type="password" /> <button type="submit" id="btnLogin">Log In</button> </fieldset> </form> 

And here is the javascript that I have so far:

 $(document).ready(function() { var options = { method: 'post', url: 'Login.aspx', beforeSubmit: function(formData, form, options) { $.each(formData, function() { log.info(this.value); }); return true; } }; $('form#form1').ajaxForm(options); }); 

(log.info () from the Blackbird debugger library I'm using)

When I click the Submit button, instead of specifying POST, I indicated that it uses GET instead, and nothing is written to my beforeSubmit function. The ajaxForm plugin doesn't seem to apply to the form at all, but I don't understand why. Can anyone help with this?

+4
source share
2 answers

I ran the following code through firebug and it seemed to work as advertised, but the formData variable in the beforeSubmit callback is empty because you did not set the name attribute in the text fields.

 <script type="text/javascript"> $(document).ready(function() { var options = { beforeSubmit: showData }; $('form#form1').ajaxForm(options); }); function showData(formData, form, options) { //var formData = [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]; $.each(formData, function(i, obj) { log.info(obj.name + " | " + obj.value); }); return true; } </script> <form id="form1" action="Login.aspx" method="post"> <fieldset id="login"> <legend>Please Log In</legend> <label for="txtLogin">Login</label> <input id="txtLogin" type="text" name="User" /> <label for="txtPassword">Password</label> <input id="txtPassword" type="password" name="Pass" /> <button type="submit" id="btnLogin">Log In</button> </fieldset> </form> 
+3
source

To begin with, according to this API , your options object must use type , not method , or simply specify a method attribute on the form in HTML.

(now I will add some small stylistic notes, you can stop reading here if you want):

  • You can replace $(document).ready(function... with $(function...
  • $.each(formData, function... looks more natural like $(formData).each(function...
+1
source

All Articles