Search code examples
elixirphoenix-framework

How to get the value of an input field in Phoenix Framework?


I am trying to get the input text from an html input, which is supposed to be a message in a chat. Then I want to add that text to the chat history below.

My (updated!) code so far:

defmodule ChatWeb.ChatLive do 
    use ChatWeb, :live_view
    
        def mount(params, session, socket) do
            {:ok, assign(socket, :text_value, "")}
        end
        
        def render(assigns) do
        ~H"""
            <h1>Chat</h1>
            <form phx-submit="submit">
            <label>Your Text:<input id="msg" type="text" name="input_value" /></label>
            <button>Send</button>
            </form>
            <div id="chat">
                Chat history: <%= @text_value %>
            </div>
            
        """
        end
        
        def handle_event("send-msg", %{"input_value" => msg}, socket) do
            {:noreply, assign(socket, :text_value, msg)}
        end
        
end

This is what it looks like so far:

enter image description here


Solution

  • You have this handle_event function:

        def handle_event("send-msg", %{"input_value" => msg}, socket) do
            {:noreply, assign(socket, :text_value, msg)}
        end
    

    ... but it doesn't look like "send-msg" is being bound to anything. Here's more info about bindings in LiveView, including a code example: https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#module-bindings

    It looks like your "Send" button is currently bound to the "submit" event, via this code:

    <form phx-submit="submit">
    

    If you just change the "send-msg" def handle_event("send-msg"... to "submit", it works fine and text_value gets assigned to the value of the input box as expected.