Skip to content

Commit 60e7f47

Browse files
authored
add note about setting properties to JS.set_attribute/1 (#3826)
Closes #3786.
1 parent b5e4703 commit 60e7f47

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

  • lib/phoenix_live_view

lib/phoenix_live_view/js.ex

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -903,6 +903,34 @@ defmodule Phoenix.LiveView.JS do
903903
show
904904
</button>
905905
```
906+
907+
> #### A note on properties {: .warning}
908+
>
909+
> `JS.set_attribute/1` cannot be used to set DOM properties such as the [`value` of an input](https://jakearchibald.com/2024/attributes-vs-properties/#value-on-input-fields).
910+
> So if you find yourself wanting to do `JS.set_attribute({"value", "..."})` on an input, and
911+
> see that updated value reflected in a form event, you should use `JS.dispatch/2`
912+
> instead:
913+
>
914+
> Instead of
915+
>
916+
> ```heex
917+
> <.button phx-click={JS.set_attribute({"value", ""}, to: "#my_input")}>...</.button>
918+
> ```
919+
>
920+
> do
921+
>
922+
> ```heex
923+
> <script :type={Phoenix.LiveView.ColocatedJS} name="clear_input">
924+
> window.addEventListener("input:clear", (e) => {
925+
> e.target.value = ""
926+
> e.target.dispatchEvent(new Event("input", {bubbles: true}))
927+
> })
928+
> </script>
929+
> <.button phx-click={JS.dispatch("input:clear", to: "#my_input")}>...</.button>
930+
> ```
931+
>
932+
> Note: this uses `Phoenix.LiveView.ColocatedJS`, but you can also define the event listener directly inside
933+
> your `app.js` instead.
906934
"""
907935
def set_attribute({attr, val}), do: set_attribute(%JS{}, {attr, val}, [])
908936

0 commit comments

Comments
 (0)