2018-10-12 03:11:57 +00:00
|
|
|
/*global URLify*/
|
2020-10-24 02:58:05 +00:00
|
|
|
'use strict';
|
|
|
|
{
|
|
|
|
const $ = django.jQuery;
|
2018-10-12 03:11:57 +00:00
|
|
|
$.fn.prepopulate = function(dependencies, maxLength, allowUnicode) {
|
|
|
|
/*
|
|
|
|
Depends on urlify.js
|
|
|
|
Populates a selected field with the values of the dependent fields,
|
|
|
|
URLifies and shortens the string.
|
|
|
|
dependencies - array of dependent fields ids
|
|
|
|
maxLength - maximum length of the URLify'd string
|
|
|
|
allowUnicode - Unicode support of the URLify'd string
|
|
|
|
*/
|
|
|
|
return this.each(function() {
|
2020-10-24 02:58:05 +00:00
|
|
|
const prepopulatedField = $(this);
|
2018-10-12 03:11:57 +00:00
|
|
|
|
2020-10-24 02:58:05 +00:00
|
|
|
const populate = function() {
|
2018-10-12 03:11:57 +00:00
|
|
|
// Bail if the field's value has been changed by the user
|
|
|
|
if (prepopulatedField.data('_changed')) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2020-10-24 02:58:05 +00:00
|
|
|
const values = [];
|
2018-10-12 03:11:57 +00:00
|
|
|
$.each(dependencies, function(i, field) {
|
|
|
|
field = $(field);
|
|
|
|
if (field.val().length > 0) {
|
|
|
|
values.push(field.val());
|
|
|
|
}
|
|
|
|
});
|
|
|
|
prepopulatedField.val(URLify(values.join(' '), maxLength, allowUnicode));
|
|
|
|
};
|
|
|
|
|
|
|
|
prepopulatedField.data('_changed', false);
|
|
|
|
prepopulatedField.on('change', function() {
|
|
|
|
prepopulatedField.data('_changed', true);
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!prepopulatedField.val()) {
|
|
|
|
$(dependencies.join(',')).on('keyup change focus', populate);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
2020-10-24 02:58:05 +00:00
|
|
|
}
|