allow to configure the minimal id to be generated

This commit is contained in:
Ferdinand Kuhl 2024-11-08 16:10:25 +01:00
parent c4c25ae2d1
commit 95bc0c861a
2 changed files with 8 additions and 6 deletions

View file

@ -1,19 +1,21 @@
/* 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'));
@ -43,7 +45,7 @@ export function formStamp(element, options = {})
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);
@ -52,7 +54,7 @@ export function formStamp(element, options = {})
'beforeStampInsert',
{
detail: {
i: initialItemCount + created,
i: startWithId + created,
node: clone
},
cancelable: true

View file

@ -1,6 +1,6 @@
{
"name": "@digicomp/form-stamp",
"version": "0.0.4",
"version": "0.0.5",
"description": "duplicates an entry form field group",
"main": "form-stamp.js",
"scripts": {