5d4b0e8c277377e225578a238ea4757013237d81
[emels.git] / emels / static / admin / js / prepopulate.js
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
16             var populate = function() {
17                 // Bail if the field's value has been changed by the user
18                 if (prepopulatedField.data('_changed')) {
19                     return;
20                 }
21
22                 var values = [];
23                 $.each(dependencies, function(i, field) {
24                     field = $(field);
25                     if (field.val().length > 0) {
26                         values.push(field.val());
27                     }
28                 });
29                 prepopulatedField.val(URLify(values.join(' '), maxLength, allowUnicode));
30             };
31
32             prepopulatedField.data('_changed', false);
33             prepopulatedField.change(function() {
34                 prepopulatedField.data('_changed', true);
35             });
36
37             if (!prepopulatedField.val()) {
38                 $(dependencies.join(',')).keyup(populate).change(populate).focus(populate);
39             }
40         });
41     };
42 })(django.jQuery);