-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathpeople.js
More file actions
77 lines (68 loc) · 2.9 KB
/
Copy pathpeople.js
File metadata and controls
77 lines (68 loc) · 2.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const People = {
add: function (template, list) {
let newForm = template.clone().html();
// Ensure the index of the new form is 1 greater than the current highest index, to prevent collisions
let index = 0;
$('.person-form', list).each(function () {
var newIndex = parseInt($(this).data('index'));
if (newIndex > index) {
index = newIndex;
}
});
// Replace the placeholder index with the actual index
newForm = $(newForm.replace(/replace-me/g, index + 1));
newForm.appendTo(list);
const nameInput = newForm.find('.person-name');
const orcidInput = newForm.find('.person-orcid');
const opts = {
orientation: 'top',
triggerSelectOnValidInput: false,
onSelect: function (suggestion) {
orcidInput.val(suggestion.data.orcid);
},
transformResult: function(response) {
return {
suggestions: $.map(response.suggestions, function(item) {
item.data.hint = item.data.orcid;
return item;
})
};
},
formatResult: Autocompleters.formatResultWithHint
}
opts.serviceUrl = list.parents('[data-role="people-form"]').data('autocompleteUrl');
opts.dataType = 'json';
opts.deferRequestBy = 100;
nameInput.autocomplete(opts);
return newForm;
},
// This is just cosmetic. The actual removal is done by rails,
// by virtue of the hidden checkbox being checked when the label is clicked.
delete: function () {
$(this).parents('.person-form').fadeOut();
},
init: function () {
$('[data-role="people-form"]').each(function () {
const form = $(this);
const template = form.find('[data-role="people-form-template"]');
const list = form.find('[data-role="people-form-list"]');
form.find('[data-role="people-form-add"]').click(function (e) {
e.preventDefault();
const nextItem = People.add(template, list);
nextItem.find('input.form-control:first').focus();
});
// Add new person if enter is pressed on final person, otherwise focus the next person in the list.
$(form).on('keyup', 'input', function (e) {
if (e.which === 13) {
e.preventDefault();
let nextItem = $(e.target).parents('.person-form').next('.person-form');
if (!nextItem.length) {
nextItem = People.add(template, list);
}
nextItem.find('input.form-control:first').focus();
}
});
});
$('.delete-person-btn input.destroy-attribute').change(People.delete);
}
};