How to populate a select field based on previous inputs?

Hi, I am trying to create a multiple choice style quiz. Currently I have a form that looks like this:

The options field uses JavaScript to add/remove new options and the user can fill them out.

Essentially, I want the user to be able to choose values in the “correct answer” select field based on the option inputs above.

For example, in this case I would want the correct_answer to have 3 select fields: “example”, “for”, “options”

What is the best way to achieve this?

Hey @PopThisCode, this question is tagged liveview, but you say you are using Javascript to add / remove options. Are you using LiveView or not?

I am not using LiveView at the moment. But I believe this problem can be solved using either JS or LiveView. I don’t have a preference, but generally, I think it’s best practice if I do use LiveView?

It’s possible to do it with JS or LiveView but it is not trivial.

One example with LiveView

On the way, You will need to know how to create multiple data at the same time, with Ecto cast_assoc or put_assoc. Or use embedded assocs.

1 Like

It can be done using LiveView, and is relatively simple if you have a good grasp on GenServers. LiveView can hook into form change events to do validation. See this example: Form bindings — Phoenix LiveView v0.17.6. In this validation step, you can change the LiveView assigns, which get referenced in the LiveView template. From there, you can iterate over the variable that you add to the assigns, and dynamically generate the <option> elements in your form. This generates a changing list of select elements before the submission stage, and is pretty useful in general.

I don’t know if it should be thought if in this way. Using LiveView is a pretty major technology decision for a project.

Yeah this 100%. There are “best practice” ways to do it with both live view and Javascript.

1 Like