Button that adds div and JS event listeners

Hi! I have a LiveView app with a form that contains an arbitrary number of fields I want the user to be able to add on the fly–there’s at first one field and then they can add as many more as they’d like by clicking a button. What I think I need to do is wire up the button so that the LiveView server inserts a new div in the page for this field and also calls a javascript function which implements some logic around mutually-exclusive field values (using some EventListeners).

Is there a recommended way to do this? One constraint I have is that my content security policy disallows inline event handlers like onClick so getting the javascript function triggered is tripping me up at the moment. I was thinking the insertion of a new div could be handled by a Phoenix function component, but I just want to make sure it’s okay to use it this way.

You can take a look at this one: Phoenix LiveView form with nested embeds and add/delete buttons · GitHub


Okay, great, thank you. That gives me a good idea of the add/delete fields approach.

If I wanted subsequent fields (these are select boxes) to be limited by the fields above them, is there a way you’d recommend doing this? Right now, I’m listening for ‘change’ events on these fields and then adding and removing options to the fields below.

You also have my gratitude for sharing this!

FWIW, you could reduce the amount of JS manipulation required by letting the change events bubble up to a handler on the enclosing element.

It’s also possible to do this in pure LiveView, using phx-change and similar.