Skip to content

Commit 2d10102

Browse files
authored
Add pure vanilla js for add a collection element
1 parent 12d52ea commit 2d10102

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

form/form_collections.rst

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ On the rendered page, the result will look something like this:
255255

256256
.. code-block:: html
257257

258-
<ul class="tags" data-prototype="&lt;div&gt;&lt;label class=&quot; required&quot;&gt;__name__&lt;/label&gt;&lt;div id=&quot;task_tags___name__&quot;&gt;&lt;div&gt;&lt;label for=&quot;task_tags___name___name&quot; class=&quot; required&quot;&gt;Name&lt;/label&gt;&lt;input type=&quot;text&quot; id=&quot;task_tags___name___name&quot; name=&quot;task[tags][__name__][name]&quot; required=&quot;required&quot; maxlength=&quot;255&quot; /&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;">
258+
<ul class="tags" data-index="{{ form.tags|length > 0 ? form.bars|last.vars.name + 1 : 0 }}" data-prototype="&lt;div&gt;&lt;label class=&quot; required&quot;&gt;__name__&lt;/label&gt;&lt;div id=&quot;task_tags___name__&quot;&gt;&lt;div&gt;&lt;label for=&quot;task_tags___name___name&quot; class=&quot; required&quot;&gt;Name&lt;/label&gt;&lt;input type=&quot;text&quot; id=&quot;task_tags___name___name&quot; name=&quot;task[tags][__name__][name]&quot; required=&quot;required&quot; maxlength=&quot;255&quot; /&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;">
259259

260260
.. seealso::
261261

@@ -340,6 +340,31 @@ you'll replace with a unique, incrementing number (e.g. ``task[tags][3][name]``)
340340
// Add the new form at the end of the list
341341
$collectionHolder.append($newFormLi)
342342
}
343+
344+
Code without jQuery library
345+
346+
.. code-block:: javascript
347+
const newItem = (e) => {
348+
const collectionHolder = document.querySelector(`.${e.currentTarget.dataset.collectionHolderClass}`);
349+
350+
const item = document.createElement("div");
351+
352+
item.innerHTML = collectionHolder
353+
.dataset
354+
.prototype
355+
.replace(
356+
/__name__/g,
357+
collectionHolder.dataset.index
358+
);
359+
360+
collectionHolder.appendChild(item);
361+
362+
collectionHolder.dataset.index++;
363+
};
364+
365+
document
366+
.querySelectorAll('.add_item_link')
367+
.forEach(btn => btn.addEventListener("click", newItem));
343368
344369
Now, each time a user clicks the ``Add a tag`` link, a new sub form will
345370
appear on the page. When the form is submitted, any new tag forms will be converted

0 commit comments

Comments
 (0)