Skip to content

Instantly share code, notes, and snippets.

@maldworth
Created November 23, 2014 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maldworth/86d4d276783fde6ac114 to your computer and use it in GitHub Desktop.
Save maldworth/86d4d276783fde6ac114 to your computer and use it in GitHub Desktop.
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);
}
};
@maldworth
Copy link
Author

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