Select element for Phoenix LiveView forms

This code is inside a form, that is already being handled with a def handle_event("validate", function. However, my issue is that I’d like to change the UI on the form based on the user selecting a value froma HTML select element. I’d like to change in what currency the amount that the user owes, is shown.

So far, I am able to change the currency using the phx-click no problem, however, with select this creates the changes when the dropdown is clicked and not when the user selects a value (what I’m looking for).

I’ve been hacking at this a couple of days with no luck. Any suggestions / pointers are welcome.

      <label>
        Amount
        <div>
          <%= number_input f, :amount, "phx-debounce":  "100" %>
          <%= select f, :var, ["USD": "usd", "EUR": "eur"], selected: base_currency, "phx-throttle": "300", "phx-value-swap": "swap" %>
        </div>
      </label>

According to the documentation, the preferred way to handle form validations is relying on the phx-change data attribute in the form element.

Extracted from Phoenix.LiveView — Phoenix LiveView v0.20.2

To handle form changes and submissions, use the phx-change and phx-submit events. In general, it is preferred to handle input changes at the form level, where all form fields are passed to the LiveView’s callback given any single input change.

Please take a look at the example code in that doc page. I think it’s a good reference.

2 Likes

In traditional web page, <select> is used with <form>. Phoenix LiveView accepts this idea and it only provides phx-change binding for forms.

If you want to track the change of a element, wrap the element with a form like:

<form phx-change="swap">
   <label>
        Amount
        <div>
          <%= number_input f, :amount, "phx-debounce":  "100" %>
          <%= select f, :var, ["USD": "usd", "EUR": "eur"], selected: base_currency, "phx-throttle": "300" %>
        </div>
  </label>
</form>
4 Likes

Thanks, have been searching for this!

Sure would be nice if we could use phx-change directly on select elements, as adding unnecessary form tags to the DOM necessitates more styling / code :stuck_out_tongue:

6 Likes