prepopulate.js 1.4 KB

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