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