2
0
mirror of https://expo.survex.com/repositories/troggle/.git synced 2024-12-19 23:12:20 +00:00
troggle/media/admin/js/prepopulate.js

44 lines
1.5 KiB
JavaScript
Raw Normal View History

/*global URLify*/
'use strict';
{
const $ = django.jQuery;
$.fn.prepopulate = function(dependencies, maxLength, allowUnicode) {
2020-06-18 21:51:19 +01:00
/*
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
2020-06-18 21:51:19 +01:00
*/
return this.each(function() {
const prepopulatedField = $(this);
2020-06-18 21:51:19 +01:00
const populate = function() {
2020-06-18 21:51:19 +01:00
// Bail if the field's value has been changed by the user
if (prepopulatedField.data('_changed')) {
return;
}
const values = [];
2020-06-18 21:51:19 +01:00
$.each(dependencies, function(i, field) {
field = $(field);
if (field.val().length > 0) {
values.push(field.val());
}
});
prepopulatedField.val(URLify(values.join(' '), maxLength, allowUnicode));
2020-06-18 21:51:19 +01:00
};
prepopulatedField.data('_changed', false);
prepopulatedField.on('change', function() {
2020-06-18 21:51:19 +01:00
prepopulatedField.data('_changed', true);
});
if (!prepopulatedField.val()) {
$(dependencies.join(',')).on('keyup change focus', populate);
2020-06-18 21:51:19 +01:00
}
});
};
}