5

I use this loop

<form action="/" method="POST">
    <template x-for="(deck, index) in $store.cart.decks">
      <div x-show="$store.cart.total(index) > 0">
        <div><span x-text="$store.cart.total(index)"></span> Karten</div>
        <div x-text="deck.price"></div> €
        <input :name="'deck[' + index + '][name]'" :value="$store.cart.decks[index].name">
      </div>
    </template>
</form>

Which works fine and displays all items in my cart and hides those that have a total of 0.

But this will only set the item with 0 on display:none, which will still transfer the data in the POST request.

  1. I tried to use x-if instead of x-show but that is only allowed on a tempate tag.

  2. I tried to add the x-if on the template tag:

    <template x-show="$store.cart.total(index) > 0" ...
    

    this results in an error, because index is not set at that point

  3. I tried to add another <template> tag inside the existing template, but then the variables index and deck are not available inside the second any more

How do I prevent the zero cart items being computed in my POST request?

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
rubo77
  • 19,527
  • 31
  • 134
  • 226
  • Another option is that, when you hide the div you also disable the input so that it is not sent in the request. – chetan Oct 19 '21 at 12:22

1 Answers1

6

I think something like the following would work, note the div inside both template elements.

<template x-for="(deck, index) in $store.cart.decks">
  <div>
    <template x-if="$store.cart.total(index)">
      <div>
        <!-- rest of the content -->
      </div>
    </template>
  </div>
</template>
Hugo
  • 3,500
  • 1
  • 14
  • 28