Adding Items to Session Storage Arrays

Thanks George, but that’s not what I meant, unless I misunderstood you. I was already using ‘add unique’, which is very useful - only adding an item if it’s not already there.

I want to remove an item if it’s already there (and add it if it isn’t). I can do it as I mentioned - using two buttons or entering an expression manually. I just wondered if there was a recommended/better way.

Lets say you have a recordset and want to store the selected ids. You add a checkbox in the repeater, set the checked state when the value exists in the array (using the contains formatter). Then using the updated event of the checkbox to add or remove the value to/from the array.

This should in theory work and should look something like:

<input
  id="checked"
  type="checkbox"
  dmx-bind:value="id"
  dmx-checked="arr.contains(this.value)"
  dmx-on:updated="this.checked ? arr.add(this.value) : arr.remove(this.value)"
>

It is late and I haven’t tested it, so go ahead and try it. There is a lot possible when you are creative. If it is not working or missing something, then ask here again and I will look for some solution tomorrow.

1 Like

Thanks Patrick. I couldn’t get this to work. However, I tried using the same method as I used for a button - but with a checkbox - and it worked fine:
<button dmx-on:click="session1.data.myarray.contains(id)?arr1.remove(id):arr1.addUniq(id)">Button</button>

Using this approach with a checkbox is a useful option - thanks.

I don’t think the above method can be using the UI. That’s why I wondered if there was a recommended way. The only method I know using the UI is by using two buttons (optionally with hide/show). Anyway, it’s no problem - all of these methods work.

I tested it today, it is indeed not possible to do it all using the UI. I noticed that you can’t do expressions in the dynamic events and also noticed that some events were missing for the checkbox.

My previous checkbox code was indeed not working, here a working version for the people that are interested.

<input
  type="checkbox"
  name="input1"
  dmx-bind:value="id"
  dmx-bind:checked="arr1.items.contains(id)"
  dmx-on:change="arr1.items.contains(id) ? arr1.remove(id) : arr1.addUniq(id)"
>

An easier way with the UI is indeed to use two buttons and using the contains formatter to show/hide the add/remove button.

<button dmx-hide="arr1.items.contains(id)" dmx-on:click="arr1.add(id)">Add</button>
<button dmx-show="arr1.items.contains(id)" dmx-on:click="arr1.remove(id)">Remove</button>
2 Likes

Thanks - no problem this time. This is a useful method for using checkboxes with arrays. However I’m having other problems which I’ve explained in another thread.

This has been improved in Wappler 5.2.1. Now there are two new dynamic events for the checkboxes - checked and unchecked, so you can run different actions depending on the checkbox status.

1 Like