45 lines
1.6 KiB
JavaScript
45 lines
1.6 KiB
JavaScript
|
/* jshint esversion: 6 */
|
||
|
const defaults = {
|
||
|
nameToReplace: 'idx',
|
||
|
removeSelector: '.remove'
|
||
|
}
|
||
|
|
||
|
export function formStamp(element, options = {})
|
||
|
{
|
||
|
const {
|
||
|
nameToReplace,
|
||
|
removeSelector
|
||
|
} = { ...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;
|
||
|
let created = 0;
|
||
|
const removeRow = (element) => () => {
|
||
|
const rowToDelete = element.closest(itemSelector);
|
||
|
// Flow renders identity fields directly at the form tag, so we need to look
|
||
|
if (rowToDelete.dataset.stampRemoveWithMe) {
|
||
|
container.closest('form')
|
||
|
.querySelectorAll(rowToDelete.dataset.stampRemoveWithMe)
|
||
|
.forEach(child => child.remove())
|
||
|
}
|
||
|
rowToDelete.remove();
|
||
|
}
|
||
|
|
||
|
element.addEventListener('click', () => {
|
||
|
const clone = template.content.cloneNode(true);
|
||
|
clone.querySelectorAll('input, select, textarea').forEach(child => {
|
||
|
child.name = child.name.replace(nameToReplace, initialItemCount + created);
|
||
|
});
|
||
|
clone.querySelectorAll(removeSelector).forEach(child => {
|
||
|
child.onclick = removeRow(child);
|
||
|
});
|
||
|
element.before(clone);
|
||
|
created++;
|
||
|
});
|
||
|
container.querySelectorAll(removeSelector).forEach(child => {
|
||
|
child.onclick = removeRow(child);
|
||
|
});
|
||
|
}
|
||
|
export default formStamp;
|