water

water

Capture Keyboard Input(barcode scanner) without input form in Liveview

I’m trying to build a Liveview with 2 parts:

  • top:
    • switch button: camera / hardware scanner
      • show camera scanner
      • or empty
  • bottom:
    • scan history table from db with pubsub: statistics, colors, time,..

When the hardware scanner is used and a scan is made, a sequence of characters is send ending with an Enter-key.

defmodule HelloWeb.ScanLive do
  use HelloWeb, :live_view


  def render(assigns) do
    ~H"""
    <div phx-window-keyup="scanner">
    </div>
    """
  end

  def handle_event("scanner", key, socket) do
    IO.inspect(key)
    {:noreply, socket}
  end
end

Is this the proper way to do this in Phoenix Liveview using handle_event with keyup?
Can you capture a sequence+Enter at once or do you have to capture separately and build it up.

Most Liked

mcrumm

mcrumm

Phoenix Core Team

If you want to capture each key individually, yes.

This requires a form input. I am curious why specifically you wish to avoid this. I can give you a working example (using an ancient Symbol LS1900 barcode scanner to demonstrate :slight_smile: ):

Here’s the code:

defmodule HelloWeb.ScanLive do
  use HelloWeb, :live_view

  def render(assigns) do
    ~H"""
    <form id="form" phx-submit={JS.push("capture") |> JS.push_focus(to: "#input")}>
      <input
        id="input"
        data-count={@count}
        type="text"
        name="code"
        autofocus
        phx-debounce="blur"
        placeholder="Scan barcode..."
        value=""
        class="w-full"
      />
      <button class="hidden" type="submit">Submit</button>
    </form>

    <ul>
      <li :for={code <- @codes}><%= code %></li>
    </ul>
    """
  end

  def mount(_, _, socket) do
    socket = socket |> assign(:count, 0) |> assign(:codes, [])
    {:ok, socket}
  end

  def handle_event("capture", %{"code" => code}, socket) do
    IO.inspect(code)

    socket =
      socket
      |> update(:count, &(&1 + 1))
      |> update(:codes, &[code | &1])

    {:noreply, socket}
  end
end

Usually there are (at least) two tricky parts. The first is clearing and re-focusing the input after the form submits. You can use a combination of JS.push() and JS.push_focus() to submit the form and re-focus the input. To ensure the input is cleared after submit, you need to force the input to re-render. In this case I am setting a data-count attribute and incrementing the count on each submit. This will force LiveView to re-render the input with the empty value provided on the element.

The other tricky part is that barcode scanners don’t always send an Enter key as a suffix. I left the phx-debounce="blur" on the input because you will definitely want that if you try to add a phx-change event to the form. Since LiveView won’t re-render focused inputs on change, you would probably want to push an event from the server and use it to reset the input value.

pdgonzalez872

pdgonzalez872

that’s so cool!

Last Post!

Norman56

Norman56

For capturing a sequence+Enter at once, I’m not sure if that’s possible. It might be easier to capture the sequence and then add the Enter key as a separate event.
Regarding your issue with the software keyboard popping up, adding inputmode=“none” to the input should fix that.

Where Next?

Popular in Questions Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

Other popular topics Top

KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36654 110
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
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 31494 112
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement