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