jQuery live(‘submit’) and form serialize() issues in IE

OK It’s been busy in the F7 camp, making it very difficult to find time to blog, hence this being my first development blog entry since before christmas.. MAD.. Admittedly we are still as busy as house elves but I came across some IE voodoo with jquery and wanted to share it with you, or at least so I can refer back!

Using: jquery 1.6.2

Right – I was trying to catch the submit event on a form, the form is loaded with ajax so I use the jquery .live() method.

$("#myForm").live('submit', function() {
    $.post($(this).attr('action'), $(this).serialize(), function(data) {
         $('#dialog').html(data);
    });
    return false;
});

I use the .serialize() to grab all form data, convert it to a nice json string and ajax post it to my php form handler.. Worked great in good browsers, Chrome and FF etc.. In internet explorer, the live(‘submit’) method was hit, but the serialize() method returned empty!

I spent hours trying to find a solution, ripping through google to find an anwser, and there were a few different solutions that I’d like to share, that didn’t help me, but could help you:

  • Check your markup! Make sure you have closed your FORM tag
  • Also make sure your form isn’t embedded in another form, best to just make your markup valid really 🙂 Although that still doesn’t all IE problems..
  • Also instead of returning false, you can use event.preventDefault();

This is all good to do anyways and seems to be the solution to everyone else that I’ve seen encounter the same symptoms, but here’s what sprung my form submit to life:

	$("body").each(function() {
		$("#myForm", this).live('submit', function(e) {
			e.preventDefault();
			$.post($(this).attr('action'), $(this).serialize();, function(data) {
				$('#dialog').html(data);
			});
		});
	});

I found the .delegate() method on the jquery site which pointed me to a way of using the live method (as above) which delegate is a shortcut for.

Essentially wrap your live(‘submit’) inside a parents ‘each’ loop. Note the ‘this’ var in the select method:

       $("#myForm", this).live ....

Hope that helps some one!