1
0
Fork 0
IdreXyz/idre/static/admin/js/prepopulate.js

43 lines
1.5 KiB
JavaScript
Raw Normal View History

2017-08-17 19:13:36 +02:00
/*global URLify*/
2015-03-14 22:38:12 +01:00
(function($) {
2017-08-17 19:13:36 +02:00
'use strict';
$.fn.prepopulate = function(dependencies, maxLength, allowUnicode) {
2015-03-14 22:38:12 +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
2017-08-17 19:13:36 +02:00
allowUnicode - Unicode support of the URLify'd string
2015-03-14 22:38:12 +01:00
*/
return this.each(function() {
var prepopulatedField = $(this);
2017-08-17 19:13:36 +02:00
var populate = function() {
2015-03-14 22:38:12 +01:00
// Bail if the field's value has been changed by the user
if (prepopulatedField.data('_changed')) {
return;
}
var values = [];
$.each(dependencies, function(i, field) {
field = $(field);
if (field.val().length > 0) {
values.push(field.val());
}
});
2017-08-17 19:13:36 +02:00
prepopulatedField.val(URLify(values.join(' '), maxLength, allowUnicode));
2015-03-14 22:38:12 +01:00
};
prepopulatedField.data('_changed', false);
prepopulatedField.change(function() {
prepopulatedField.data('_changed', true);
});
if (!prepopulatedField.val()) {
$(dependencies.join(',')).keyup(populate).change(populate).focus(populate);
}
});
};
})(django.jQuery);