Skip to content

Instantly share code, notes, and snippets.

@grahampcharles
Created March 5, 2014 23:09
Show Gist options
  • Save grahampcharles/9378692 to your computer and use it in GitHub Desktop.
Save grahampcharles/9378692 to your computer and use it in GitHub Desktop.
jquery function to automatically submit a form each time a control is changed
/*
Usage:
Add a class of "autosubmit" to controls. If the control is not within a form
(or even if it is but you want to use a different form), add data-autosubmit-form="#selector".
Then, on DOM ready, execute autosubmit() to wire up the handlers:
$(function () {
autosubmit();
});
*/
function autosubmit() {
function submitFormFor(element) {
// get form
var formSelector = $(element).data("autosubmit-form"),
$form = formSelector ?
$(formSelector) :
$(element).closest("form");
if ($form.length > 0) { $form.submit();}
}
// wire-up autosubmit
$("input.autosubmit[type='checkbox'],input.autosubmit[type='radio']").on("click", function () {
submitFormFor(this);
});
$("select.autosubmit").on("change", function () {
if ($(this).is(":focus")) {
submitFormFor(this);
}
});
$("input.autosubmit[type='text'],textarea.autosubmit").on("blur keyup", function (e) {
if (e.type === "blur" || e.which === 13) {
submitFormFor(this);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment