Search code examples
alpine.js

Show content if certain checkboxes are checked


I want to show a block of content if certain checkboxes in a group are selected.

This partially works:

<div x-data="{ show: false }">
  <div>
    <label class="flex" for="category-1">
      <input class="mr-2" type="checkbox" id="category-1" value="A" x-model="show">
      <span class="inline-block">A</span>
    </label>
    <label class="flex" for="category-2">
      <input class="mr-2" type="checkbox" id="category-2" value="B">
      <span class="inline-block">B</span>
    </label>
    <label class="flex" for="category-3">
      <input class="mr-2" type="checkbox" id="category-3" value="C" x-model="show">
      <span class="inline-block">C</span>
    </label>
  </div>
  <div x-show="show" x-collapse>This will be hidden until a checkbox is selected.</div>
</div>

Codepen

But if you check one box, it checks all of them that have x-model on them.

What do I need to do so only the checkbox you click gets checked while also still revealing the content?


Solution

  • You can use an array instead of a single value:

        <div x-data="{ checks: [],
                       showIfAC: function() { return this.checks.includes('A') || this.checks.includes('C'); },
        }">
    
            <div x-text="checks"> </div>   <!-- for debugging -->
    
            <div>
    
                <label class="flex" for="category-1">
                    <input class="mr-2" type="checkbox" id="category-1" value="A" x-model="checks">
                    <span class="inline-block">A</span>
                </label>
    
                <label class="flex" for="category-2">
                    <input class="mr-2" type="checkbox" id="category-2" value="B" x-model="checks">
                    <span class="inline-block">B</span>
                </label>
    
                <label class="flex" for="category-3">
                    <input class="mr-2" type="checkbox" id="category-3" value="C" x-model="checks">
                    <span class="inline-block">C</span>
                </label>
    
            </div>
    
            <div x-show="showIfAC()" x-collapse x-cloak>
                This will be hidden until a checkbox is selected.
            </div>
    
        </div>
    

    The array will contain the values ​​of the selected checkboxes, then you can choose the way you prefer to check if at least one value is included in the array (here I have used the showIfAC() method)