Struggling to use the for-loop feature in Alpine.js to dynamically display the titles of items

I'm puzzled as to why I am unable to execute the for loop using Alpine.js and dynamically display the title of each item. I have attempted to utilize the store within the script HTML tag in order to iterate over an array of objects and retrieve the title key of each object.

// html

<div class="content__mid"  x-for="item in $store.products.items" :key="item.id">
    <p class="content__mid-item" x-text="item.title"></p> // the content is currently empty
</div>

<script>
      document.addEventListener('alpine:init', () => {
        Alpine.store('products', {
        items: [
          {
            id: 1,
            title: 'Aspirin',
            country: 'USA',
            manufacturer: 'Bangladesh',
            price: '120',
            validDate: '02.10.2024'
          },
          {
            id: 2,
            title: 'Aspirin',
            country: 'Italy',
            manufacturer: 'Bangladesh',
            price: '120',
            validDate: '02.10.2024'
          },
          {
            id: 3,
            title: 'Aspirin',
            country: 'Austria',
            manufacturer: 'Bangladesh',
            price: '140',
            validDate: '02.10.2024'
          }
        ],
      })
    })
    </script>

Answer №1

Make sure to declare the x-for directive on a <template> element:

<div class="content__mid" x-data="">
  <template x-for="item in $store.products.items" :key="item.id">
    <p class="content__mid-item" x-text="item.title"></p>
  </template>
</div>

Remember, an empty x-data directive is necessary for each Alpine.js component. You can remove it if any parent element already has one.

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

Having trouble hiding the hamburger menu depending on the screen width

I'm trying to figure out how to hide the hamburger menu when the screen width exceeds 400px. You can check out the site at damf.co Currently, the hamburger menu appears when the screen width is less than 400px. If you click on it and then expand the ...

Remove an element from a List in Java

Here is the code snippet I have written: public void tick { for (Integer i : list) { list.add(i-1); list.remove(i); System.out.println(list); } } In my scenario, I am working with a list containing integer values. Durin ...

Ways to trigger the jQuery click function using a designated element rather than $(this)

Within my code, I have a method set up like this; $('.kaldir').click(function () { var thisCheck = $(this); ..... } In addition, my HTML input field(s) are structured in this manner; <input type="radio" name="chbBesDi ...

Resetting the randomness in a function within a sudoku generator implemented in JavaScript

I'm in the process of creating a unique Sudoku generator that incorporates randomness into its design. Within my code, there's a particular function responsible for generating the Sudoku puzzles. The issue I'm encountering is the inability t ...

the function is failing to retrieve accurate information from an array

One issue I'm facing is that my code compiles and runs fine, but the values stored for the minScore and minName variables remain at 0. static void Main(string[] args) { int count = 0; string[] names = new string[MAX_SIZE]; int[] scores = new ...

How to simulate keyboard events when a dropdown list is opened in an Angular application

Requirement- A situation arises where upon opening the dropdown menu, pressing the delete key on the keyboard should reset the index to -1. Steps to reproduce the issue: 1. Click on the dropdown and select an option from the menu. 2. Click on the dropdow ...

`How can I trigger a JavaScript event when the content of an input field is modified?`

Currently, I am working on implementing validation in JavaScript. My goal is to provide the user with an alert whenever they modify the value of an input field. <input type="text" name="onchange" id="onchange" size="35" maxlength="50" /> ...

When using Javascript, the CanvasRenderingContext2D.drawImage function may not properly detect Image data

function ImageLoader() { this.imageBuffer = []; } ImageLoader.prototype.load = function(src) { var temp = new Image(); temp.src = src; this.imageBuffer.push(temp); } Recently, I've been attempting to display a grid of images on the canvas. After deb ...

Utilizing ReactDOM.render in an event listener to prevent the rendering of costly components

I have built a React application that displays a list of tasks with due dates. I want to allow users to click on the due date to bring up a datepicker for selecting a new one. Utilizing the Material-UI library from http://www.material-ui.com/#/components/ ...

Determine the total count of subarrays that have a specified value, with the value being a variable

I encountered an issue while trying to implement the solution provided in response to this query: Count values in subarray The code does not seem to be working with variables. For example, the following code snippet works: echo count(array_filter($tasks, ...

Consumer using ActiveMQ-Stomp is not receiving any messages

I attempted to create a JavaScript code for an ActiveMQ subscriber that would subscribe to a specific topic, but unfortunately I am not receiving any messages after establishing the connection. The topic that needs to be subscribed to is COO.2552270450083 ...

What is the best way to convert the javascript code into clojurescript?

Looking to utilize capacitor/app in order to determine the state (background or active) of my iOS app. My project is built on Clojurescript, so I need to convert the following javascript code into a clojurescript equivalent. Javascript import { App } fro ...

Using jQuery.load() to Retrieve Data From an External JavaScript File

When I try to load an external page using the code snippet: $('#myContainer').load('myfile.html'); I am encountering issues where the script file otherscript.js within myfile.html is not being loaded for some users. Despite testing ...

Problem encountered when trying to show the Jquery Ajax response on an HTML page

I'm facing a challenge with loading a page that needs to display values with dynamic pagination. To retrieve these values, I am making a REST call which returns a JSON object. Although I can see the JSON output in the browser console, I am unable to d ...

User login using Node.js without the need for a database, solely relying on a JavaScript array

Thank you for taking the time to assist me. I am new to node.js and JavaScript, so I have a lot to learn. For a college assignment, I need to create a login feature without user registration. Instead, I am populating a default users array in JS, solely for ...

Save the value of a webpage element into a variable and utilize it across multiple JavaScript files in TestCafe

We are working in the insurance domain and have a specific scenario that we want to achieve using TestCafe: 1st step: Login into the application 2nd step: Create a claim and store the claim number in a global variable 3rd step: Use the globally declared c ...

Create an array in JavaScript that represents a normal distribution based on the provided minimum, maximum, mean, and sample size

Consider the following scenario: min = 1 max = 5 Ave = 3 size = 5 At this stage, we have [1,?,?,?,5] How can I determine the missing numbers? (It's simple -> [1,2,3,4,5] - but how do I create a JavaScript function to return this array) ...

The scripts within the body tag are failing to load

After trying to embed angular into the body tag, I noticed that nothing is loading up. Upon inspecting the resources panel, I found that only files from the head are present. Moving all the scripts to the head section resolves the issue and everything load ...

Ways to trigger a separate function once the asynchronous task has been finished?

I am currently working on an application using AngularJS and TypeScript. In the constructor, I have a load function that is called like this: private load(): angular.IPromise<void> { const progTokInit: string = 'initial'; this.$sc ...

Dynamically adjust the gage value

Currently, I am working on a fitness application that involves showcasing BMI data using a gauge. However, I am struggling to figure out how to dynamically change the value of the gauge. In addition, when trying to implement the gauge script on button cl ...