nesimtunc

nesimtunc

How to get selected value of HTML options element on phx-click event

Hi,

Basically I’m coding an order system. There’re Products, Customer, Order and OrderItems tables.

My Order form is like attached capture.

Here’s my codes:
lib/myapp_web/live/admin/form_component.html.leex

<h2><%= @title %></h2>

<%= f = form_for @changeset, "#",
  id: "order-request-form",
  phx_target: @myself,
  phx_submit: "save" %>

  <%= label f, :customer_id %>
  <%= text_input f, :customer_id %>
  <%= error_tag f, :customer_id %>

  <%= label f, :order_id %>
  <%= text_input f, :order_id %>
  <%= error_tag f, :order_id %>

  <h2>Order Items</h2>
  <table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Count</th>
      <th></th>
    </tr>
  </thead>
  <tbody id="products">
  <tr>
    <td>
      <%= select f, :product_id, Enum.map(@products, &{&1.name, &1.id })%>
    </td>
    <td>
      <%= select f, :count, 1..50 %>
      <%= error_tag f, :count %>
    </td>
    <td>
      <button type="button" phx-click="add">+</button>
    </td>
  </tr>
  </tbody>
</table>

<h2>Cart</h2>
  <table id="cart" phx-update="append">
  <thead>
    <tr>
      <th>Name</th>
      <th>Price</th>
      <th>Count</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <%= for item <- @cart_items do %>
      <tr id="item-<%= item.id %>">
        <td><%= item.name %></td>
        <td><%= item.price %></td>
        <td></td>
        <td>
          <button type="button" phx-click="remove">-</button>
        </td>
      </tr>
    <% end %>
  </tbody>
</table>

<%= submit "Save", phx_disable_with: "Saving..." %>

</form>

lib/myapp_web/live/admin/index.ex

defmodule MyAppWeb.AdminLive.Index do
  use MyAppWeb, :live_view

  alias MyApp.{ Products, Orders }

  @impl true
  def mount(_params, _session, socket) do
    socket = socket |> assign(:pending_orders, load_pending_orders())
    {:ok, socket, temporary_assigns: [cart_items: []]}
  end

  @impl true
  def handle_params(params, _url, socket) do
    IO.inspect(params)
    IO.inspect(socket.assigns)
    {:noreply, apply_action(socket, socket.assigns.live_action, params)}
  end

  @impl true
   def handle_event("add", params, socket) do
      IO.puts("+++++++++++++++++ADDING+++++++++++++++++++")
      IO.inspect(params)
      IO.inspect(socket.assigns.cart_items)
      IO.puts("+++++++++++++++++ADDED+++++++++++++++++++")
      cart_items = socket.assigns.cart_items
      socket = assign(socket, :cart_items, cart_items)
		{:noreply, socket}
  end

  @impl true
  def handle_event("remove", params, socket) do
    IO.puts("+++++++++++++++++REMOVING+++++++++++++++++++")
    IO.inspect(params)
    IO.inspect(socket.assigns.cart_items)
    IO.puts("+++++++++++++++++REMOVED+++++++++++++++++++")
    cart_items = socket.assigns.cart_items
    socket = assign(socket, :cart_items, cart_items)
		{:noreply, socket}
   end

  defp apply_action(socket, :new, _params) do
    socket
    |> assign(:page_title, "New Order")
    |> assign(:order_request, nil)
    |> assign(:products, load_avaliable_products())
    |> assign(:cart_items, [%Products.Product{}])
  end

  defp apply_action(socket, :index, _params) do
    socket
    |> assign(:page_title, "Admin")
    |> assign(:pending_orders, load_pending_orders())
  end

  defp load_pending_orders do
     Orders.list_pending_orders()
  end

  defp load_avaliable_products do
	Products.list_avaliable_products()
  end

end

What I need is, getting selected values of ordered products when click the “+” button on server side.

How can I achieve this?

Thank you!

Marked As Solved

jayjun

jayjun

Add :phx_change to your <form> to get every input value update. Then assign selected input values into phx-value attributes.

<%= f = form_for @changeset, "#",
  id: "order-request-form",
  phx_target: @myself,
  phx_change: "change",
  phx_submit: "save" %>

<button type="button" phx-click="add"
  phx-value-product-id="<%= @add_product_id %>"
  phx-value-count="<%= @add_count %>">+</button>
def handle_event("change", params, socket) do
  # find product_id and count in params
  socket =
    socket
    |> assign(socket, :add_product_id, product_id)
    |> assign(socket, :add_count, count)

  {:noreply, socket}
end

def handle_event("add", %{"product_id" => product_id, "count" => count}, socket) do
  ...
end

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
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
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
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

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 30048 115
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
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
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
AstonJ
You’re a programmer, so you don’t need spoon feeding with the conventional drivel about “this is an integer.” No. You need to know what’s...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New

We're in Beta

About us Mission Statement