Simple way to get value of input field?

I am very new to the Phoenix Framework. All I am trying to do is 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.

I don’t need changesets, databases and I think I don’t even need forms (?). All I want to do is get the input and concatenate it to an ever longer chat log. :smiley:

My 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>
            <label>Your Text:<input id="msg" type="text" /></label>
            <button phx-click="send-msg">Send</button>
            <div id="chat">
                Chat history: <%= @text_value %>
            </div>
            
        """
        end
        
        def handle_event("send-msg", _, socket) do
            msg = "what do I do here?"
            {:noreply, assign(socket, :text_value, msg)}
        end
        
end

Thanks so much in advance!

Hi @athsche welcome! To be valid HTML, inputs have to be contained inside a form. You also need to make sure to give your input a name. Finally, you want to use a phx-submit on the form because you’re trying to connect the clicking of the button to the submission of the text input.

Here is an example that should work (although I haven’t had a chance to run it myself)

        def render(assigns) do
        ~H"""
            <h1>Chat</h1>
            <form phx-submit="submit">
            <label>Your Text:<input id="msg" type="text" name="text_value" /></label>
            <button>Send</button>
            </form>
            <div id="chat">
                Chat history: <%= @text_value %>
            </div>
            
        """
        end
        
        def handle_event("send-msg", %{"text_value" => msg}, socket) do
            {:noreply, assign(socket, :text_value, msg)}
        end
3 Likes

Thanks very much!
Unfortunately the message is not added to the chat history, i.e. text_value variable. I will try to look into that. But already this has helped my general understanding of the framework a lot.