svb

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

codeanpeace

Welcome!

Here’s three distinct things to consider:

  1. listening for user interaction with a generic JS event listener on the textarea input e.g. on key down for the Enter keycode
  2. handling that event by triggering a phx-submit event on the form e.g. dispatching a “submit” event
  3. 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

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 :slight_smile:

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})
      )
    }
  })
}

Last Post!

axelclark

axelclark

I was running into a similar issue. I ended up pushing an event after creating a new message then clearing the field when I receive the event in the frontent.

in form_component.ex

    case Chats.create_message(message_params) do
      {:ok, _message} ->
        {:noreply,
         socket
         |> push_event("clear-textarea", %{id: "message_content"})
         |> push_patch(to: socket.assigns.patch)}

in app.js

window.addEventListener(`phx:clear-textarea`, (e) => {
  let el = document.getElementById(e.detail.id)
  el.value = ""
})

Where Next?

Popular in Questions Top

JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New

Other popular topics Top

vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 49266 226
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New

We're in Beta

About us Mission Statement