Skip to content

Instantly share code, notes, and snippets.

@barrypitman
Forked from postpostmodern/ie_button_fix.js
Created May 11, 2011 07:43
Show Gist options
  • Save barrypitman/966065 to your computer and use it in GitHub Desktop.
Save barrypitman/966065 to your computer and use it in GitHub Desktop.
Fixes <button> elements in IE <=7
// IE doesn't deal well with button elements.
// The following jQuery code fixes the two most common issues:
// 1. All button values being submitted whether they were clicked or not
// 2. Button labels being submitted instead of the value of the value attribute
// Make sure you have loaded jQuery, of course.
// Improvements:
// 1. Cleanly handles the case where a form submit handler prevents form submission (the buttons were left disabled previously)
// 2. Only applies fix to IE 7 and lower, as problem is fixed in IE8.
jQuery(function() {
//fixed in IE8
if (!($.browser.msie && parseInt($.browser.version) <= 7)) {
return;
}
// bind a form submit handler when the submit button is clicked, i.e. as late as possible so that
// it will be the last submit handler in the chain.
$('button[type=submit]').click(function() {
var closestForm = $(this).closest('form');
//save the button that was clicked for use by the form submit handler
closestForm.data('clickedButton', $(this));
//also bind to 'form-pre-serialize' to play nicely with the ajax form plugin, http://jquery.malsup.com/form/
closestForm.bind('submit.ie-button-fix form-pre-serialize.ie-button-fix', formSubmit);
});
function formSubmit(e) {
try {
//retrieve the clicked button (we saved it earlier)
var clickedButton = $(this).data('clickedButton');
//if a previous handler cancelled form submission, don't modify buttons, just return
if (e.isDefaultPrevented() || clickedButton == null) {
return;
}
// Disable all buttons (keeps their values from being submitted)
$('button').attr('disabled', 'disabled');
// Get the text label of the button
var label = clickedButton.html();
// Set it to an empty string so IE will read the real value attribute
clickedButton.text('');
// if the clicked button has a name attribute, copy it to a hidden field
var name = clickedButton.attr('name');
var value = clickedButton.attr('value');
if (name != null && value != null) {
// Create a hidden field with the name and value of the button
clickedButton.after($("<input/>").attr('type', 'hidden').attr('name', name).val(value));
}
// Restore the button's text label
clickedButton.html(label);
} finally {
//unbind the formSubmit handler
$(this).unbind('.ie-button-fix');
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment