Click Submit Custom Binding for Form Validation
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
This comment has been minimized.
Allows non
<input>
button to submit a form and still take advantage of HTML5 form validation. See it in action in this Jsfiddle