Created
November 23, 2014 17:50
-
-
Save maldworth/86d4d276783fde6ac114 to your computer and use it in GitHub Desktop.
Click Submit Custom Binding for Form Validation
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
ko.bindingHandlers.clickSubmit = { | |
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) { | |
var formElement = null; | |
// Allow the binding handler to function with or without jQuery | |
if(typeof jQuery == 'undefined') { | |
// We need to have a parameter provided to the handler if jQuery is not present | |
var value = ko.utils.unwrapObservable(valueAccessor()); | |
if(!value) | |
// Need to have a value which contains the name of our parent form. | |
throw new Error('You must provide a parameter for the binding "clickSubmit" if you are not using jQuery.'); | |
formElement = document.forms[value]; | |
} else { | |
var jqFormElement = $(element).closest('form'); | |
formElement = jqFormElement.get(0); | |
} | |
if(!formElement) { | |
throw new Error('"clickSubmit" binding could not find the parent form') | |
} | |
// Create our input submit button (which will be not displayed) | |
var hiddenSubmit = document.createElement('input'); | |
hiddenSubmit.setAttribute('type','submit'); | |
hiddenSubmit.style.display = 'none'; | |
formElement.appendChild(hiddenSubmit); | |
// Wrap our new element in a function closure, so we can pass this to the framework's click binding | |
var newFunction = function() { | |
return function() { | |
hiddenSubmit.click(); | |
}; | |
}; | |
ko.bindingHandlers.click.init(element, newFunction, allBindings, viewModel, bindingContext); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Allows non
<input>
button to submit a form and still take advantage of HTML5 form validation. See it in action in this Jsfiddle