prepopulate.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /*global URLify*/
  2. (function($) {
  3. 'use strict';
  4. $.fn.prepopulate = function(dependencies, maxLength, allowUnicode) {
  5. /*
  6. Depends on urlify.js
  7. Populates a selected field with the values of the dependent fields,
  8. URLifies and shortens the string.
  9. dependencies - array of dependent fields ids
  10. maxLength - maximum length of the URLify'd string
  11. allowUnicode - Unicode support of the URLify'd string
  12. */
  13. return this.each(function() {
  14. var prepopulatedField = $(this);
  15. var populate = function() {
  16. // Bail if the field's value has been changed by the user
  17. if (prepopulatedField.data('_changed')) {
  18. return;
  19. }
  20. var values = [];
  21. $.each(dependencies, function(i, field) {
  22. field = $(field);
  23. if (field.val().length > 0) {
  24. values.push(field.val());
  25. }
  26. });
  27. prepopulatedField.val(URLify(values.join(' '), maxLength, allowUnicode));
  28. };
  29. prepopulatedField.data('_changed', false);
  30. prepopulatedField.change(function() {
  31. prepopulatedField.data('_changed', true);
  32. });
  33. if (!prepopulatedField.val()) {
  34. $(dependencies.join(',')).keyup(populate).change(populate).focus(populate);
  35. }
  36. });
  37. };
  38. })(django.jQuery);