How to dynamically add html elements?

Is it possible to inject HTML elements depending on a variable count? For example, if I have 1 employee, inject 1 email address field. If I have 10 employees then inject 10 email address fields?

I found the answer here :thread: Collection List (weweb.io) :slight_smile:

Ok so this works for a collection but how can I inject HTML columns depending on a number entered by a user?

Hi,
I found a hacky way of doing it, might be what you need waiting for a weweb integrated option.
If you just need a define number of element that are all the same, you can use the collection list of the column component.
In the item field, bind the value to :

return new Array(variables['inputUid-value'])

variables[‘inputUid-value’] being the field where your user select a number.
In order to get every input of each collection item you first need to change the input element’s HTML attribut class to the “yourElementClass” you want. Once it’s done, in a workflow (such as a submit button workflow) you will need a variable with the array type and edit its value (with a change variable value block) to :

return Array.from(
   document.getElementsByClassName("yourElementClass"))
      .map(e => e.value)
)

It become harder if you need to display specific data for every collumn or if you need to add individual submit button for every collection item you have
If your data are stored in a collection, you can change your item field to :

return collections['collectionUID'].data.slice(0,variables['inputUid-value'])

In order to have individual submit button, you need a way to identifie your collection item’s input. To do that, you will need to change the item field to :

return new Array(variables['inputUid-value']).fill().map((_, idx) => 0+ idx)

This will give you number to identifie every collection item you have.
Now that you have your collection and your input field in every item collection, you will be able to identifie each input by binding there HTML attributes id to :

return "identifier" + context.item.data

Now, in your button’s workflow, you can get the input of the input that is in the same collection item :

document.getElementsByClassName("identifier"+context.item.data))

Hope this help you !

You can use two nested column elements.
Look at this examole of a dynamic grid.
In the example you can see also a sample of the data controlling the grid.
If you change the data you change the grid too, so adding a column is just modifying the underlying data.

1 Like

+1 to @dorilama , its always better to not touch the DOM, and manipulate the data use to generate it. It’s avoid a lot of bugs due to conflict between Vue and what your script is doing