Skip to content

Instantly share code, notes, and snippets.

@waynehoover
Created June 20, 2012 20:29
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 waynehoover/2962024 to your computer and use it in GitHub Desktop.
Save waynehoover/2962024 to your computer and use it in GitHub Desktop.
(jQuery), function (a) {
a.fn.autosaveField = function (b) {
var c = a.extend({}, a.fn.autosaveField.defaults, b);
return this.each(function () {
var b = a(this);
if (b.data("autosaved-init")) return;
var d = b.attr("data-field-type") || ":text",
e = b.find(d),
f = b.attr("data-action"),
g = b.attr("data-name"),
h = e.val(),
i = function () {
b.removeClass("errored"), b.removeClass("successful"), b.addClass("loading"), a.ajax({
url: f,
type: "POST",
data: {
_method: c.method,
field: g,
value: e.val()
},
success: function () {
b.addClass("successful"), h = e.val()
},
error: function () {
b.attr("data-reset-on-error") && e.val(h), b.addClass("errored")
},
complete: function () {
b.removeClass("loading")
}
})
};
d == ":text" ? (e.blur(function () {
a(this).val() != h && i()
}), e.keyup(function () {
b.removeClass("successful"), b.removeClass("errored")
})) : d == "input[type=checkbox]" && e.change(function () {
b.removeClass("successful"), b.removeClass("errored"), i()
}), b.data("autosaved-init", !0)
})
}, a.fn.autosaveField.defaults = {
method: "put"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment