form.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. (function ($) {
  2. /**
  3. * Retrieves the summary for the first element.
  4. */
  5. $.fn.drupalGetSummary = function () {
  6. var callback = this.data('summaryCallback');
  7. return (this[0] && callback) ? $.trim(callback(this[0])) : '';
  8. };
  9. /**
  10. * Sets the summary for all matched elements.
  11. *
  12. * @param callback
  13. * Either a function that will be called each time the summary is
  14. * retrieved or a string (which is returned each time).
  15. */
  16. $.fn.drupalSetSummary = function (callback) {
  17. var self = this;
  18. // To facilitate things, the callback should always be a function. If it's
  19. // not, we wrap it into an anonymous function which just returns the value.
  20. if (typeof callback != 'function') {
  21. var val = callback;
  22. callback = function () { return val; };
  23. }
  24. return this
  25. .data('summaryCallback', callback)
  26. // To prevent duplicate events, the handlers are first removed and then
  27. // (re-)added.
  28. .unbind('formUpdated.summary')
  29. .bind('formUpdated.summary', function () {
  30. self.trigger('summaryUpdated');
  31. })
  32. // The actual summaryUpdated handler doesn't fire when the callback is
  33. // changed, so we have to do this manually.
  34. .trigger('summaryUpdated');
  35. };
  36. /**
  37. * Sends a 'formUpdated' event each time a form element is modified.
  38. */
  39. Drupal.behaviors.formUpdated = {
  40. attach: function (context) {
  41. // These events are namespaced so that we can remove them later.
  42. var events = 'change.formUpdated click.formUpdated blur.formUpdated keyup.formUpdated';
  43. $(context)
  44. // Since context could be an input element itself, it's added back to
  45. // the jQuery object and filtered again.
  46. .find(':input').andSelf().filter(':input')
  47. // To prevent duplicate events, the handlers are first removed and then
  48. // (re-)added.
  49. .unbind(events).bind(events, function () {
  50. $(this).trigger('formUpdated');
  51. });
  52. }
  53. };
  54. /**
  55. * Prepopulate form fields with information from the visitor cookie.
  56. */
  57. Drupal.behaviors.fillUserInfoFromCookie = {
  58. attach: function (context, settings) {
  59. $('form.user-info-from-cookie').once('user-info-from-cookie', function () {
  60. var formContext = this;
  61. $.each(['name', 'mail', 'homepage'], function () {
  62. var $element = $('[name=' + this + ']', formContext);
  63. var cookie = $.cookie('Drupal.visitor.' + this);
  64. if ($element.length && cookie) {
  65. $element.val(cookie);
  66. }
  67. });
  68. });
  69. }
  70. };
  71. })(jQuery);