Best practices for manipulating the DOM

We have a simple case where a form has two dropdowns. The options in the second rely on the choice of the first.

In rails, our go-to pattern for this was as follows:

  • Create the template to render whatever the default state of the dropdowns is.
  • Create an action that returns just the options tags for the submitted choice.
  • Using JS, when the first selection box is changed, make an ajax call to that new action. On response, swap out the old DOM element containing the old options with the new options.

At first, I thought LiveView was the go to on this, but after looking at LiveView, it seems like the entirety of the app needs to be written as a LiveView app. This is not, and it’s already pretty massive. Too massive to make the adjustment.

Then, I thought Channels might be the answer, but it looks like channels is a way to talk server → client.

So, how are people doing this daily in the Phoenix world?


If you do not want to use LiveView, you can use the same pattern that you were using with Rails. I see nothing wrong with it in principles.

That said, you do not need to convert the whole app to LiveView in order to use it in one specific place.

OH! Does LiveView seem like overkill or more work to solve the above problem? I read up a bit on liveview, and it seemed like a great way to handle such things. But i didn’t know I could use it on such a limited basis

LiveView is definitely a good way to solve your problem. The docs even list it as one of the common use-cases:

Handling of user interaction and inputs, buttons, and forms - such as input validation, dynamic forms, autocomplete, etc;

That said, it’s also perfectly fine to use plain JS for something like this. I’d say it’s up to you, maybe if populating this particular select box is your only need, and you feel more comfortable with plain JS, it might be overkill to introduce LiveView. But if you think it might turn out to be useful in other cases too, this could be an opportunity to start to gradually adopt it.

1 Like

thanks so much for your input. This phase has some serious deadline issues, so I will probably use JS… but Phase II is a little more open, so I will figure out how to do this.


1 Like