Correct usage of checkboxes in LiveView

Hello everyone,

currently I have a dropdown menu with different options and I want to display the selected options right above the dropdown. So my trimmed down HTML Template looks like this:

<div>
  <input name="disciplines" type="text" readonly value="<%= Enum.join(@checked_disciplines, ", ") %>">
    <div>
      <%= for element <- @disciplines do %>
       <div>
         <%= checkbox(:discipline, :disciplines, phx_click: "toggle_discipline", phx_target: @myself, phx_value_id: element) %>
        <label for="<%= element %>"><%= element %></label>
       </div>
      <% end %>
    </div>
</div>

My ex files has the following logic:

def mount(socket) do
    socket =
      assign(socket,
        disciplines: [
          "Football",
          "Basketball"
        ],
        checked_disciplines: []
      )

    {:ok, socket}
  end

def handle_event("toggle_discipline", %{"id" => id}, socket) do
    checked_disciplines = [id | socket.assigns.checked_disciplines]

    socket =
      assign(socket,
        checked_disciplines: checked_disciplines
      )

    {:noreply, socket}
  end

When I click on the checkbox to select an entry the checkbox isn’t checked. It’s just checked when I remove the socket assign in the event handling because the component isn’t rerendered.

I’m sure that there is a way, to determine for the checkbox function if the box needs to be checked or unchecked. I think I have to change my variable structure because the checkbox function is currently unable to determine if the values are checked or not because the checked values are inside my checked_disciplines variable.

The documentation unfortunately didn’t help me. It’s specific to Phoenix and I’m not sure how to transfer this knowledge to LiveView.

I really appreciate your help!

1 Like