Skip to content

How to force an input value in Phoenix LiveView

When a input field is in focus, any changes that are done to the value won't be applied. This is done to avoid changes from the server overwriting the value a user is typing.

However sometimes it is handy to set the value anyway, for example when accepting a query suggestion in a search autocomplete UI.


Add a hook that reacts on events from the server:

const ForceInputValue = {
mounted() {
({ value }) => (this.el.value = value)
let liveSocket = new LiveSocket("/live", Socket, {
hooks: { ForceInputValue },
params: { _csrf_token: csrfToken },


Add the hook to the input field:

value="<%= @query %>"
name="query" />


Push an event to the client when you want to force a value on an input even though it is in focus.

def handle_event(
%{"key" => "ArrowRight"},
%{assigns: %{suggestion: suggestion}} = socket
) do
{:noreply, socket |> push_event("force-input-value", %{value: suggestion})}


  • Inspired by this comment


These notes are unpolished collections of thoughts, unfinished ideas, and things I want to remember later. In the spirit of learning in public, I'm sharing them here. Have fun exploring, if you want!
© 2022 by Adrian Philipp