Compare commits
2 commits
Author | SHA1 | Date | |
---|---|---|---|
95bc0c861a | |||
c4c25ae2d1 |
2 changed files with 13 additions and 6 deletions
|
@ -1,20 +1,25 @@
|
|||
/* jshint esversion: 6 */
|
||||
const defaults = {
|
||||
nameToReplace: 'idx',
|
||||
removeSelector: '.remove'
|
||||
removeSelector: '.remove',
|
||||
minimalId: 'auto'
|
||||
}
|
||||
|
||||
export function formStamp(element, options = {})
|
||||
{
|
||||
const {
|
||||
nameToReplace,
|
||||
removeSelector
|
||||
removeSelector,
|
||||
minimalId
|
||||
} = { ...defaults, ...element.dataset, ...options };
|
||||
const container = element.parentElement;
|
||||
const template = element.querySelector('template');
|
||||
const itemSelector = '.' + template.content.firstElementChild.className.replace(/ /g, '.');
|
||||
const initialItemCount = container.querySelectorAll(itemSelector).length;
|
||||
const startWithId = minimalId === 'auto' ? container.querySelectorAll(itemSelector).length : parseInt(minimalId);
|
||||
let created = 0;
|
||||
const afterDomManipulation = () => {
|
||||
element.dispatchEvent(new CustomEvent('afterStampDomManipulation'));
|
||||
}
|
||||
const removeRow = (removeItem) => () => {
|
||||
const rowToDelete = removeItem.closest(itemSelector);
|
||||
// Flow renders identity fields directly at the form tag, so we need to look
|
||||
|
@ -33,13 +38,14 @@ export function formStamp(element, options = {})
|
|||
}
|
||||
))) {
|
||||
rowToDelete.remove();
|
||||
afterDomManipulation();
|
||||
}
|
||||
}
|
||||
|
||||
element.addEventListener('click', () => {
|
||||
const clone = template.content.cloneNode(true);
|
||||
clone.querySelectorAll('input, select, textarea').forEach(child => {
|
||||
child.name = child.name.replace(nameToReplace, initialItemCount + created);
|
||||
child.name = child.name.replace(nameToReplace, startWithId + created);
|
||||
});
|
||||
clone.querySelectorAll(removeSelector).forEach(child => {
|
||||
child.onclick = removeRow(child);
|
||||
|
@ -48,13 +54,14 @@ export function formStamp(element, options = {})
|
|||
'beforeStampInsert',
|
||||
{
|
||||
detail: {
|
||||
i: initialItemCount + created,
|
||||
i: startWithId + created,
|
||||
node: clone
|
||||
},
|
||||
cancelable: true
|
||||
}
|
||||
))) {
|
||||
element.before(clone);
|
||||
afterDomManipulation();
|
||||
created++;
|
||||
}
|
||||
});
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@digicomp/form-stamp",
|
||||
"version": "0.0.3",
|
||||
"version": "0.0.5",
|
||||
"description": "duplicates an entry form field group",
|
||||
"main": "form-stamp.js",
|
||||
"scripts": {
|
||||
|
|
Loading…
Add table
Reference in a new issue