Toggle-all isn't applying checkbox on every entry

I am following this tutorial: bulk_delete
But when i select the toggle-all checkbox it is not selecting the checkbox of every entry below in the table.
And giving me this error:

[error] GenServer #PID<0.3801.0> terminating
** (Protocol.UndefinedError) protocol Enumerable not implemented for "checked" of type BitString

Here’s my code:

<th>
<input type="checkbox" name="toggle-all" id="toggle-all" phx-click="toggle-all" phx-update="ignore" />
 </th>
<% checked = if (file.id in @toggle_ids), do: "checked", else: IO.inspect(@toggle_ids)%>
            <tr id={"file-#{file.id}"}>
                <td>
                <input type="checkbox" name="toggle" phx-click="toggle"
                phx-value-toggle-id={file.id} {checked} />
                </td>
                 //other fields
             </tr>

This is my index.ex code:

@impl true
  def handle_event("toggle-all", %{"value" => "on"}, socket) do
    file_ids = socket.assigns.files |> Enum.map(& &1.id)
    # IO.inspect(file_ids)
    {:noreply, assign(socket, :toggle_ids, file_ids)}
  end

  def handle_event("toggle-all", %{}, socket) do
    {:noreply, assign(socket, :toggle_ids, [])}
  end

  def handle_event("toggle", %{"toggle-id" => id}, socket) do
    id = String.to_integer(id)
    toggle_ids = socket.assigns.toggle_ids
    IO.inspect(toggle_ids)

    my_toggle_ids =
      if id in toggle_ids do
        Enum.reject(toggle_ids, &(&1 == id))
      else
        [id | toggle_ids]
      end

    {:noreply, assign(socket, :toggle_ids, my_toggle_ids)}
  end

If you use the interpolation in html tags without an attribute, it must contain a keyword list (or map) with your values. In your case you could replace your

<% checked = if (file.id in @toggle_ids), do: "checked", else: IO.inspect(@toggle_ids) %>

with

<% checked = if (file.id in @toggle_ids), do: [checked: true], else: [] %>

or write it as

<% checked = file.id in @toggle_ids %>
...
<td>
  <input type="checkbox" name="toggle" phx-click="toggle" 
    phx-value-toggle-id={file.id} checked={checked} />
</td>
1 Like

Thank you soo much. Like i was stuck in it from around couple of hours. And now, Solved!!!
Thanks again. :smiley:

1 Like