svb
Form submit on Enter keypress for textarea input type
Hi!
Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a newline to my input field (which is expected behaviour).
Is there a way to make submit work on pressing the Enter key without messing up the way the form is cleared after submitting?
I’m using below code to make the form work. This form works properly when the type of the input element is the default text type rather than a “textarea”.
<div class="flex items-center py-2">
<.form for={@form} phx-submit="save" phx-change="update" phx-target={@myself} >
<.input type="textarea" field={@form[:content]} placeholder="Start typing..." autocomplete="off"/>
<.button class="text-black" phx-disable-with="Submit">
Submit
</.button>
</.form>
</div>
Cheers,
Sil
Marked As Solved
codeanpeace
Welcome!
Here’s three distinct things to consider:
- listening for user interaction with a generic JS event listener on the textarea input e.g. on key down for the Enter keycode
- handling that event by triggering a
phx-submitevent on the form e.g. dispatching a “submit” event - attaching the JS event listener/handler to the textarea input of a LiveView form e.g. LiveView client hooks via
phx-hook
All together that might look something like:
<input type="textarea" ... phx-hook="TextArea" />
let Hooks = {}
Hooks.TextArea = {
mounted() {
this.el.addEventListener("keydown", e => {
if (event.key == "Enter") {
event.preventDefault();
this.el.form.dispatchEvent(
new Event("submit", {bubbles: true, cancelable: true})
)
}
})
}
}
let liveSocket = new LiveSocket("/live", Socket, {hooks: Hooks, ...})
Also Liked
svb
Thanks for the quick reply!
Works like a charm. I think the way the submit event is triggered from this hooks is a neat solution ![]()
I’ve added a check on the Shift key so that form will not submit on Shift+Enter and instead will add a newline to the textarea:
mounted() {
this.el.addEventListener("keydown", e => {
if (e.key == "Enter" && e.shiftKey == false) {
e.preventDefault();
this.el.form.dispatchEvent(
new Event("submit", {bubbles: true, cancelable: true})
)
}
})
}
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








