Skip to content

Instantly share code, notes, and snippets.

Created November 23, 2014 17:50
What would you like to do?
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());
// 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'); = 'none';
// Wrap our new element in a function closure, so we can pass this to the framework's click binding
var newFunction = function() {
return function() {;
};, newFunction, allBindings, viewModel, bindingContext);
Copy link

Allows non <input> button to submit a form and still take advantage of HTML5 form validation. See it in action in this Jsfiddle

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment