Last active
August 29, 2015 14:16
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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