-
-
Save benjy8001/f6ea1ab12c80bfb819e8ba8198a69f33 to your computer and use it in GitHub Desktop.
Polyfill for Form Attribute on Submit Buttons
This file contains 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
/** | |
* The form attribute can be used to associate a submit button with a form, even | |
* if the button is not a child of the <form> itself. | |
* | |
* This polyfill detects support and polyfills the functionality using jQuery. | |
*/ | |
(function() { | |
function formAttributeSupport() { | |
// detect if browser supports this | |
var sampleElement = $('[form]').get(0); | |
var isIE11 = !(window.ActiveXObject) && "ActiveXObject" in window; | |
if (sampleElement && window.HTMLFormElement && (sampleElement.form instanceof HTMLFormElement || sampleElement instanceof window.HTMLFormElement) && !isIE11) { | |
// browser supports it, no need to fix | |
return true; | |
} | |
return false; | |
}; | |
function checkAndSubmitForm(form) { | |
// Form is invalid! | |
if (!form.checkValidity()) { | |
// Create the temporary button, click and remove it | |
var tmpSubmit = document.createElement('button') | |
form.appendChild(tmpSubmit) | |
tmpSubmit.click() | |
form.removeChild(tmpSubmit) | |
} else { | |
form.submit() | |
} | |
} | |
if ( !formAttributeSupport() ) { | |
$( document ) | |
.on( "click", "button[form]", function( event ) { | |
event.preventDefault() | |
let formId = $( this ).attr( "form" ) | |
checkAndSubmitForm(document.querySelector( "#" + formId )) | |
}) | |
.on( "keypress", "form input", function( event ) { | |
let $form | |
if ( event.keyCode === 13 ) { | |
$form = $( this ).parents( "form" ) | |
let formId = $form.attr("id") | |
if ( $form.find( "button[form]" ).length === 0 && | |
$( "button[form][form=" + formId + "]" ).length > 0 ) { | |
checkAndSubmitForm(document.querySelector( "#" + formId )) | |
} | |
} | |
}); | |
} | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment