Yesterday presented a problem I was unfamiliar with, and while ie6 continues to be the bain of all web developers existance, I finally was able to emerge triumphant, with the head of the demon tucked nicely under my arm… for now. The problem of course is trying to submit a form through javascript with ie6.
After poking around the large interweb I stumbled on another site that had run into the same problem. a slightly more indepth description of the problem is that you have a form, but rather than use a submit button, you have an image wrapped in an a-tag that you have assigned a click-event too that submits the form (or sends it to some js validation, and then submits the form). This is all fine-and-dandy with any ‘modern’ web browser, but for some reason that only m$ can tell us, when ie6 follows the a-tag, it gets lost without ever submitting the form, it doesn’t even attempt to load the page.
Some people have reported that adding an empty anchor to your a-tag fixes the problem (you know, a simple >a href=’#'<), but we like code that validates, so we usually insert ye olde ‘javascript:void(null);’ into our a-tags when we handle them with onclicks, or jQuerify them.
The solution that we ended up using was to use a setTimeout(); around the form submit in the js. For some reason, this allows ie6 to remember what it was supposed to do and get it done. I like to think of it as a virtual kick in the teeth to the browser. Anyway, here is some sample code to help you visualize the problem and solution.
Here is our form, (yes, it has a smattering of JSTL in it Image may be NSFW.
Clik here to view. , you can ignore that if it bothers you)
And here is our sample javascript code BEFORE being fixed (note the jQuery goodness, that I can’t use enough of)
$(document).ready(function(){
$(".submit a").click(function(){
$("#reportForm").submit();
});
});
Note that the above code works fine in Opera 9+, Safari 3+, Firefox 3+ (and most-likey but untested in Firefox 2+), and yes even the black-sheep of the browser family ie7 can render and run this code just fine.
Here is the fixed javascript…
$(document).ready(function(){
$(".submit a").click(function(){
setTimeout('$("#reportForm").submit();', 50);
});
});
Yep, that’s it, a very subtle change, just inserting the setTimeout() method fixes the ie6 stupidity.