1 import {onChildEvent} from "../services/dom";
2 import {uniqueId} from "../services/util";
6 * Allows easy row add/remove controls onto a table.
7 * Needs a model row to use when adding a new row.
12 this.modelRow = this.$refs.model;
13 this.addButton = this.$refs.add;
14 this.removeSelector = this.$opts.removeSelector;
15 this.rowSelector = this.$opts.rowSelector;
16 this.setupListeners();
20 this.addButton.addEventListener('click', this.add.bind(this));
22 onChildEvent(this.$el, this.removeSelector, 'click', (e) => {
23 const row = e.target.closest(this.rowSelector);
30 const clone = this.modelRow.cloneNode(true);
31 clone.classList.remove('hidden');
32 this.setClonedInputNames(clone);
33 this.modelRow.parentNode.insertBefore(clone, this.modelRow);
34 window.components.init(clone);
38 * Update the HTML names of a clone to be unique if required.
39 * Names can use placeholder values. For exmaple, a model row
40 * may have name="tags[randrowid][name]".
41 * These are the available placeholder values:
42 * - randrowid - An random string ID, applied the same across the row.
43 * @param {HTMLElement} clone
45 setClonedInputNames(clone) {
46 const rowId = uniqueId();
47 const randRowIdElems = clone.querySelectorAll(`[name*="randrowid"]`);
48 for (const elem of randRowIdElems) {
49 elem.name = elem.name.split('randrowid').join(rowId);
54 export default AddRemoveRows;