Skip to content

Instantly share code, notes, and snippets.

@jaysylvester
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaysylvester/9508bd7ba0b678b13d01 to your computer and use it in GitHub Desktop.
Save jaysylvester/9508bd7ba0b678b13d01 to your computer and use it in GitHub Desktop.
A function that duplicates submit inputs as hidden inputs, for browsers that don't include the submit name/value when form.submit() is called
// Some browsers don't include the submit button's value when form.submit() is
// called. This function creates a click listener that duplicates a form's submit
// button as a hidden field so its name/value can be included in AJAX POSTs,
// allowing different processing based on different submit buttons.
// The only argument is a selector that represents the form you want to bind,
// such as '#login-form'.
// Copyright © 2015 Jason Sylvester. MIT License:
// http://opensource.org/licenses/MIT
function submitSurrogate(formSelector) {
var form = document.querySelector(formSelector);
form.addEventListener('click', function (e) {
var input = document.createElement('input'),
previousActions = form.querySelectorAll('input[type="hidden"].submit-surrogate');
for ( var i = 0; i < previousActions.length; i++ ) {
form.removeChild(previousActions[i]);
}
if ( e.target.type && e.target.type.toLowerCase() === 'submit' ) {
input.name = e.target.name;
input.type = 'hidden';
input.value = e.target.value;
input.className = 'submit-surrogate';
form.appendChild(input);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment