How do I get values from different select fields with JS hooks?

Hey guys, I’m currently learning Phoenix with Liveview. I’m trying to use JS hooks for getting values from 2 different select fields in a form (without using form submit). I do understand how to link liveview to JS hooks but I could not find a way to get onchange values from the select, and send it to a handle_event function no my liveview.

Basically, I want to do a kind of “onChange”, receiving the select values ​​in real time.

Here’s my render function:

def render(assigns) do
  ~L"""
    <form phx-change="filter">
      <select name="from" id="from">
        <option value="ETC">ETC</option>
        <%= for c <- @currencies do %>
          <option value="<%= Enum.at(c, 0) %>">
            <%= Enum.at(c, 0) %>
          </option>
        <% end %>
      </select>

      <select name="to" id="from">
        <option value="ADA">ADA</option>
        <%= for c <- @currencies do %>
        <option value="<%= Enum.at(c,0) %>">
          <%= Enum.at(c, 0) %>
            </option>
          <% end %>
      </select>
    </form>
  """
end

Thanks for your time, guys.

You do not have any hook setup to trigger. See JS Interop docs with some examples on how to do it.

But in brief, when you add the hook(s) you can get the value from the form, and the just hook.pushEvent("event-name", payload) from the hook, and it will trigger a handle_event("event-name", data, socket) in the LiveView.

2 Likes