Daniel
Daniel

Reputation: 2554

Trigger change on value of form field change

I have a liveview form and a text input:

<%= search_input :filter, :search, id: "filter_search_field", class: "input", placeholder: "Search", value: @search_field, "phx-debounce": "300"%>

Now there is a moment when I want to clear this field programatically, I do this by changing the assign:

{:noreply, assign(socket, :search_field, "")}

The problem with this is that the phx-change event assigned to the form is not triggered.

I also tried to create a JS hook and change the value of the field from the hook, however that does not create event either.

Upvotes: 2

Views: 2826

Answers (1)

Daniel
Daniel

Reputation: 2554

As it turns out, changing value is not enough to trigger change, a change event should be emitted, on user input that event is triggered. More information can be found here.

There are few approaches to handling this now:

  1. Creating a hook for input and emit change event on input change. The downside of this is that you will get duplicate events on user input.
  2. Adding the hook to the button (in my case I have a reset button). From here you can trigger the event manually.

What I ended up doing is a little different. Hooks have a method called pushEvent, so I used that to trigger the handle_event:

Hooks.TestHook = {
  updated(){
    this.pushEvent("filter", {_target: ["filter", "search"], filter: {search: ""}});
  }
}

The variant with creating a custom change event can be found here.

Upvotes: 2

Related Questions