Alpine declined the action of toggling a list with x-show

My goal is to create a toggleable list of items using Alpine & x-show. I want the list to be visible when the page loads and allow the user to toggle it as needed. Although the button works correctly and the JavaScript is set up properly, the list itself does not toggle (it only flickers if I include x-transition). Bootstrap is used for icons and classes.

<div x-data="{ selectedDays: ['Tue', 'Wed', 'Fri', 'Sat'], isThisOpen: false }">
    <div class="card mt-3">
        <div class="card-body">
            <button="#" @click="isThisOpen = !isThisOpen">
                <div class="d-flex align-items-center" x-bind:style="{'cursor': 'pointer'}">
                    <i class="bi bi-calendar3 h3 me-3 mb-3"></i>
                    <p class="sidebar-header mb-3 h5">Training Days</p>
                    <div class="ms-auto">
                        <i class=" fas fa-angle-left" x-cloak x-show="isThisOpen"></i>
                        <i class=" fas fa-angle-left fa-rotate-90" x-show="!isThisOpen"></i>
                    </div>
                </div>
            </button>
            <div class="btn-group d-grid justify-content-s-center col-6 mx-auto"
                 role="group" x-show="!isThisOpen" x-transition
            >
                <template x-for="day in ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']">
                    <label class="btn btn-primary rounded"
                           :class="{ 'active': selectedDays.includes(day) }"
                    >
                        <input type="checkbox"
                               x-model="selectedDays"
                               :value="day"
                               style="display: none;"
                        >
                        <span x-text="day"></span>
                    </label>
                </template>
            </div>
        </div>
    </div>
</div>

I've checked the page, reviewed the documentation, and searched for JS errors. What's frustrating is that I have implemented similar code successfully on the same page before, such as this example:

<li x-data="{ isOpen: false }" class="goal-hierarchy">
    <button="#" @click="isOpen = ! isOpen">
        <div class="d-flex align-items-center" x-bind:style="{'cursor': 'pointer'}">
            <div>
                <i class="h3 bi bi-star-fill me-3"></i>
                <span class="h5">Goals Priority</span>
            </div>
            <div class="ms-auto">
                <i class=" fas fa-angle-left" x-show="!isOpen"></i>
                <i  class="fas fa-angle-left fa-rotate-90" x-cloak x-show="isOpen"></i>
            </div>
        </div>
    </button>
     <div x-data="{ items: ['Strength', 'Size', 'Power', 'Cardio'],
                   swapItems: function(indexA, indexB) {
                         let temp = this.items[indexA];
                         this.items[indexA] = this.items[indexB];
                         this.items[indexB] = temp; } }"
         x-show="isOpen" x-cloak x-transition>

Answer №1

Your solution worked flawlessly for me, with just a couple of tweaks needed:

  • Eliminate ="#" from

    <button="#" @click...

  • Adjust the logic of isThisOpen: initialize it as true, and where you have x-show="isThisOpen", switch to x-show="!isThisOpen" and vice versa (so that the box is open when isThisOpen is false)

Revision

The issue arises due to a clash with the d-grid class in Bootstrap
To resolve this, wrap the affected <div> with an external <div> managing the display on/off:

<div x-show="!isThisOpen" x-transition>
    <div class="btn-group d-grid justify-content-s-center col-6 mx-auto" role="group" > <!--x-transition-->
        <template x-for="day in ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']">
            <label class="btn btn-primary rounded" :class="{ 'active': selectedDays.includes(day) }">
                <input type="checkbox" x-model="selectedDays" :value="day" style="display: none;">
                <span x-text="day"></span>
            </label>
        </template>
    </div>
</div>

Additionally, swapped x-class with :class in the <label>, and x-value with :value in the checkbox - which should address the button problem too

NOTE
For successful implementation, I've utilized:

<script defer src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b8cfc2dec7c0cbc4dddcbf929dd0d1">[email protected]</a>/dist/cdn.min.js"></script>

to integrate the Alpine.js library

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for updating the border color of a button:

Struggling to alter the border color of a button Attempting borderColor attribute proved futile: borderColor: '#FFFFFF' Anticipated result Code snippet: headerBtn: { backgroundColor: 'black', fontSize: '16px', f ...

Is there a way to customize the color of the like button?

I'm trying to create a Twitter-like button with an icon that changes color. When the button is clicked, it successfully changes from gray to red. But now I'm stuck on how to make it switch back from red to gray. I am currently using javascript ...

The 'Required' attribute in HTML is malfunctioning

The 'required' attribute is not functioning properly when I try to submit the form. I've searched online for a solution, but none of them have resolved my problem. Take a look at the code snippet below - I've used the required attribute ...

What is the best way to retrieve the ID of a post request using React's axios hook?

My goal is to make a post request to create an app, and then establish its links. To achieve this, I need to obtain the id of the newly created items in order to create the links. Is there a way to retrieve the id of the item created through the post reque ...

Ways to navigate to a different page in React when a user clicks?

When working on my react app, I encountered an issue where the useHistory hook was undefined. How can I troubleshoot this problem and ensure that useHistory is properly defined? App.js import 'bootstrap/dist/css/bootstrap.css' import React f ...

Combining functions in React is a powerful way to create

Is there a way to create a single function that combines handleSelectAll and handleSelectNone for toggling options in a list of categories? Instead of using a toggle (on/off) approach, I believe having separate buttons for Select All and Select None is mor ...

Steps for creating a node.js and ejs file to deploy on 000webhost

I have developed a simple todo-app using node.js and ejs templating. My goal is to host it using 000webhost, a free web-hosting service. I successfully hosted a react app for free on this platform by running "npm run build", which converted the ...

Changing the name of a specific attribute in a JSON Object for showcasing it in an HTML Table

Suppose I have fetched a list of objects from a database: [{ "id":0 ,"name":"John", "lastname":"Shell" },{ "id":1,...]; and want to display this data using the dynatable plugin: data : JSON.stringify(data) success: function(data,status){ $( ...

The `appendTo` function in Ajax is used to swap out the current element

I have been working on sending form data to a Servlet using JQuery and then receiving the response from the same JQuery. Check out the code snippet below. <%-- Document : index Created on : Feb 23, 2015, 8:18:52 PM Author : Yohan --% ...

Express.js encountering an `ERR_HTTP_HEADERS_SENT` issue with a fresh Mongoose Schema

My Objective Is If data is found using the findOne() function, update the current endpoint with new content. If no data is found, create a new element with the Schema. Issue If there is no data in the database, then the first if statement throws an ERR_H ...

Are the props.children handled differently within the <Route> component compared to other React components?

Each and every react component undergoes a process in the following function, which is located in ReactElement.js within node_modules: ReactElement.createElement = function (type, config, children){ . . . } This function also encompasses <Rou ...

Problem with JQUERY Galleria CSS positioning alignment specifically in Firefox, Chrome works without issues

I recently incorporated jquery Galleria into my website and I am currently facing an alignment issue with the div element gallery-container. Interestingly, it appears correctly aligned in Chrome but is shifted to the right in Firefox. You can view the webs ...

Issue with Mongoose's deep population feature not functioning as expected

I'm currently working on a web application that requires the use of mongoose-deep-populate. I've already installed it using npm, but unfortunately, I keep encountering the following error: Error: Plugin was not installed at Query.deepPopulate (/ ...

No data returned from Ajax GET request

Utilizing Ajax with JavaScript, I am processing data on a PHP page using the GET method. Is it possible to send data from the PHP page when the GET query is empty? My goal is to have a live search feature that filters results based on user input. When a us ...

When the NPM package is imported as a whole, it shows up as undefined. However, when it

I've come across a peculiar issue in my code where importing the textile/hub package in Node.js and then destructuring it later results in an error. However, if I destructure it while importing, the program runs without any issues. Can anyone shed som ...

What could be the reason behind the occurrence of an invalid hook error when utilizing an imported function

I'm currently working on creating a navigation bar for a dashboard page, but I've run into an issue. Everything works fine until I try to integrate the navbar by importing and executing the function. I can pinpoint that the problem occurs when in ...

How can we parse the returned 'data' as HTML in JavaScript/jQuery to select more elements?

After receiving data from a webservice, it turns out that the data is just raw HTML without any XML headers or tags around it, but simply a piece of HTML code. <div class="Workorders"> <div id="woo_9142" class="Workorder"> <span ...

Issue with Jquery function not executing on second attempt

/** Creates a table of iTunes data in HTML format **/ var appendValues = function(songArray) { songArray.each(function() { var title = $(this).find("im\\:name").eq(0).text(); var songImage = $(this).find("im\\:image").eq(0).text(); var ...

The console is displaying an undefined error for _co.photo, but the code is functioning properly without any issues

I am facing an issue with an Angular component. When I create my component with a selector, it functions as expected: it executes the httpget and renders a photo with a title. However, I am receiving two errors in the console: ERROR TypeError: "_co.photo ...

Guide on transferring three js variable to an HTML label element

For my project, I am looking to pass three js values to the label of a div. The desired output is: stWay: stProposer: stTime: hello John 2017-09-07 I have successfully programmed a button to make div1 a ...