Selecting/unselecting in a LV stream

As many of you have encountered if you want to select an active item inside a rendered stream, and only that item.
I recently rewrote a LV to use streams instead of an assign, and had the problem when I changed the active item, the previously active would not deselect.
I was looking for a way to resolve this using CSS and came to the following solution.

<style>
  li[phx-value-id="<%= @selected %>"] {
    border-width: 2px;
    border-color: rgb(34 197 94);
  }
</style>

<ul>
  <li :for={{dom_id, item} <- @streams.items phx-value-id={item.billing_id} id={dom_id}>
  ...
  </li>
</ul>

This works, now if only I could find a way to write it with tailwind…

Please don’t do this CSS-only approach to your users. Use a checkbox if you value your users.

Ok, explain?

Maybe something like

<li :for={{dom_id, item} <- @streams.items} class={if item.billing_id == @selected, do: "border-2 border-green-500", else: "" end} id={dom_id}>

Hi, thanks for your suggestion, that is what I had before.
Problem with this is that when @selected changes, nothing changes in the rendered stream.

Maybe you could have a selected property on your item directly and when you select one, you update the previously selected one and the newly selected one with stream_insert?

Add a boolean selected field to your items and add to your markup a checkbox “bound” to the boolean field. When you select an item, do a stream_insert to update your item with selected: true, and another stream_insert to deselect the currently selected field.

1 Like

And then I need to load both from the db, assuming I know what the previous selected was.

What is your beef with the CSS solution?

It’s a hack. You want to select something but are not using semantic HTML which means it will be awful in terms of accessibility. Selection without elements that can be selected. I’d go as far as using a set of radio buttons, if there can be only one selected item. Maybe even a form.

The radio button may indeed be a cleaner solution. I am not worried about accessibility in this site as it’s an internal tool. Thanks, we live and learn.

1 Like

You’re correct. Your approach taught me another way too!