Posted By

kendsnyder on 03/22/12


Tagged

plugin jquery autosave


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

BrockSamsom


jQuery autosave plugin


 / Published in: jQuery
 

jQuery plugin to save individual form fields each time something changes. Usage: $('#MyForm').autosave(url, options); where url defaults to form.method and options defaults to $.fn.autosave.defaultOptions

(UNTESTED)

  1. // jQuery plugin to save individual form fields each time something changes.
  2. // Usage: `$('#MyForm').autosave(url, options);`
  3. // where `url` defaults to form.method
  4. // and `options` defaults to $.fn.autosave.defaultOptions
  5. // (UNTESTED)
  6. ;(function($) {
  7. $.fn.autosave = function(url, options) {
  8. // build options based on defaultOptions and passed options
  9. options = $.extend({}, $.fn.autosave.defaultOptions, options || {});
  10. // `this` is the jQuery collection
  11. return this.each(function() {
  12. // `this` is the <form> element
  13. if (!this.elements) {
  14. return;
  15. }
  16. url = url || this.action;
  17. options.method = options.method || this.method;
  18. var $idElement = $(options.idElement || this.elements[options.idElementName]);
  19. if ($idElement.length == 0) {
  20. return;
  21. }
  22. $(this.elements).change(function() {
  23. // `this` is the input element that changed
  24. var queryString =
  25. options.idField + '=' + encodeURIComponent($idElement.val()) +
  26. options.columnField + '=' + encodeURIComponent(this.name) +
  27. options.valueField + '=' + encodeURIComponent($(this).val())
  28. ;
  29. if (options.useImage) {
  30. var img = new Image(url + '?' + queryString);
  31. }
  32. else {
  33. $.ajax($.extend({
  34. url: url,
  35. method: options.method,
  36. data: queryString
  37. }, options.ajaxOptions));
  38. }
  39. });
  40. });
  41. };
  42. $.fn.autosave.defaultOptions = {
  43. idElement: null,
  44. idElementName: 'id',
  45. idField: 'id',
  46. columnField: 'column',
  47. valueField: 'value',
  48. method: null,
  49. ajaxOptions: {},
  50. useImage: false
  51. };
  52. })(jQuery);

Report this snippet  

You need to login to post a comment.