targeting a specific form with serialize()

thewinchester picture thewinchester · Oct 20, 2009 · Viewed 13.3k times · Source

Following on from my previous question, which was so quickly answered by Meder it wasn't funny, there's now an additional question that's popped up in the process of making a reusable jQuery form submitted that doesn't take the user away from where they were.

Problem

The jQuery serialize() function is performing its magic on all forms within a page, and not the specific form which was submitted. Example code below.

How do I capture the form's unique name/id, and replace "form" within $("form").serialize() with the name of the target form so only that is serialised?

Form code

<form name="contact" id="contact" action="">
  <input name="_recipients" type="hidden" value="[email protected]" />
  <input name="_subject" type="hidden" value="Title" />
  ...
    <fieldset>
      <label for="name" id="name_label">Name</label>
      <input type="text" name="name" id="name" size="30" value="" class="text-input" />
      <label class="error" for="name" id="name_error">This field is required.</label><br />

      <label for="email" id="email_label">Return Email</label>
      <input type="text" name="email" id="email" size="30" value="" class="text-input" />
      <label class="error" for="email" id="email_error">This field is required.</label><br />

      <label for="phone" id="phone_label">Return Phone</label>
      <input type="text" name="phone" id="phone" size="30" value="" class="text-input" />
      <label class="error" for="phone" id="phone_error">This field is required.</label><br/>

        <br />
      <input type="submit" name="submit" class="button" id="submit_btn" value="Send your suggestion" />
    </fieldset>
  </form>

jQuery serialise and post

    var dataString = $("form").serialize();
    //alert (dataString);return false;

    $.ajax({
      type: "POST",
      url: "/_global/assets/scripts/formmail/formmail.asp",
      data: dataString,
...

Answer

meder omuraliev picture meder omuraliev · Oct 20, 2009
var dataString = $('#contact').serialize()

If you are attaching an event handler to a button or the form's submit event then you can refer to it with this if inside the submit event handler function scope, eg

$('#contact').submit(function() {
 alert( $(this).serialize() );
});

I highly recommend reading http://docs.jquery.com/Selectors