I ran into a nasty bug recently that was totally unexpected. I had a form that needed to be submitted to multiple possible locations such as submit item and save draft. I am trying to chill on JQuery overuse lately so I Googled a solution for this. Turns out I'm in luck! You can have multiple submit buttons with the same name but different values. Whichever one you click will be submitted, while the other won't. Yay!
So I thought.
Here's an example form. It just submits to itself and displays the value of the "action" button submitted. Check the source:
Give it a try yourself and see what happens. Try it in IE6, IE7, then in a modern browser. Go ahead, I'll wait. In case you don't have these installed, here's IE6:
and here's IE7:
In both IE6 and IE7, It treats buttons strangely. It submits the text between the button tags rather than the value of the button. WTF? On top of that, IE6 just submits the value as the last submit button in the source order with that name, no matter which button you click. WTF! At least it seems to work as expected in IE8 and IE9.
So how do we fix it? With some JQuery duct tape.
First we strip the
value attributes of the buttons. Retard IE can't figure them out. We'll replace them with some twitter bootstrap style metadata:
<button data-value="value one" class="btn" type="submit">Submit One</button>
<button data-value="value two" class="btn" type="submit">Submit Two</button>
Then we add a hidden input for the
action. We set a default value so the enter key will still work:
<input type="hidden" name="action" value="one" />
Then we add some simple jquery to the top:
// on clicking one of the submit buttons
// get the data-value and assign it to the hidden action field
var submit_val = $(this).attr('data-value');
// form submit, just to allow js to set the value before submitting
Now we're all set! The
Check it out
click event always fires before the
submit event, even in IE6. It sets the value of the hidden input and submits the form. Here's our working file:
, it's working!