Is there a way to retrieve the data selected in my modal window when a button is clicked, depending on the v-for value?

As someone who is new to Vue and utilizing Bootstrap modals to showcase product information, I have grid containers that contain a product image, description, and two buttons. One of the buttons, labeled More details >>, is intended to trigger a modal window displaying the same product description and image from the specific grid container.

<div id="myapp">
  <h1> {{ allRecords() }} </h1>
  <div class="wrapper" >
    <div class="grid-container" v-for="product in products" v-bind:key="product.ID">
      <div class="Area-1">
        <img class="product_image" src="https:....single_product.jpg"> 
      </div>
      <div class="Area-2">
        <div class = "amount">
          {{ product.amount }}
        </div>
        {{ product.Description }}
      </div>
      <div class="Area-3">
        <b-button size="sm" v-b-modal="'myModal'" product_item = "'product'">
          More Details >>
        </b-button>
        <b-modal id="myModal" >
          <h1> {{ product.Name }} </h1>
          <h3> {{ product.Description }} </h3>
        </b-modal>
      </div>
      <div class="Area-4">
        <br><button>Buy</button>
      </div>
    </div>
  </div>
</div>
var app = new Vue({
  'el': '#myapp',
  data: {
    products: "",
    productID: 0
  },
  methods: {
    allRecords: function(){
      axios.get('ajaxfile.php')
        .then(function (response) {
          app.products = response.data;
        })
        .catch(function (error) {
          console.log(error);
        });
    },
  }
})

Areas 1, 2, and 4 are functioning correctly, showing the product data as expected for each grid container through the v-for directive. However, Area 3 presents an issue where clicking the More details >> button only results in a faded black screen. I am unsure of what mistake is made here and would greatly appreciate some guidance.

Answer №1

Create a new property called selectedProduct in your code. On the click event of the More Details button, make sure to assign the current product to the selectedProduct member as shown below :

HTML

  <div class="Area-3">
    <b-button size="sm" v-b-modal="'myModal'" 
             @click="selectProduct(product)">More Details >> </b-button>    
    <b-modal id="myModal">
             <h1> {{ this.selectedProduct.Name }} </h1>
             <h3> {{ this.selectedProduct.Description }} </h3>
    </b-modal>
  </div>

Javascript:

var app = new Vue({
 'el': '#myapp',
 data: {
    products: "",
    productID: 0,
    selectedProduct: {Name: '', Description: '', Amount:0}
 },
 methods: {
   allRecords: function(){
   ...
   },
   selectProduct: function(product)
   {
       this.selectedProduct = product;
   }
   ...
 }

Answer №2

I couldn't reproduce the issue, so I decided to create a JSFiddle for testing:

https://jsfiddle.net/4289wh0e/1/

Upon testing, I noticed that multiple modal elements popped up when clicking on the "More Details" button.

My recommendation is to have only one modal within the wrapper and to store the selected product in a data variable.

https://jsfiddle.net/4289wh0e/2/

<div id="myapp">
    <h1> {{ allRecords() }} </h1>

    <div class="wrapper">

        <div class="grid-container" v-for="product in products" v-bind:key="product.ID">

            <div class="Area-1"><img class="product_image" src="https:....single_product.jpg"> </div>

            <div class="Area-2">
                <div class="amount">{{ product.amount }} </div>
                {{ product.Description }}</div>

            <div class="Area-3">
                <b-button size="sm" v-b-modal="'productModal'" @click="chooseProduct(product)" product_item="'product'">More Details >> </b-button>

            </div>

            <div class="Area-4">
                <br>
                <button>Buy</button>
            </div>
        </div>

        <b-modal id="productModal" v-if="chosenProduct">
            <h1> {{ chosenProduct.Name }} </h1>
            <h3> {{ chosenProduct.Description }} </h3>
        </b-modal>
    </div>
</div>
Vue.use(BootstrapVue)

var app = new Vue({
    'el': '#myapp',
    data: {
        products: [],
        chosenProduct: null
    },
    methods: {
            chooseProduct: function (product) {
            this.chosenProduct = product
        },
        allRecords: function(){
                    this.products = [
            {
                ID: 1,
                Description: 'dek',
              Name: 'Name',
              amount: 100
            },
            {
                ID: 2,
                Description: 'dek 2',
              Name: 'Name 2',
              amount: 300
            }
          ]
        },
    }
})

Answer №3

If all you see is a black screen, it's because the b-modal in your v-for loop doesn't have a unique ID assigned to it. This causes all modals to open simultaneously when the button is clicked, creating a dark backdrop on the screen.

To fix this issue, consider using the product's ID (assuming it's unique) as part of the modal's ID to ensure its uniqueness.

<div id="myapp">
  <h1> {{ allRecords() }} </h1>
  <div class="wrapper" >
    <div class="grid-container" v-for="product in products" v-bind:key="product.ID">
      <div class="Area-1">
        <img class="product_image" src="https:....single_product.jpg"> 
      </div>
      <div class="Area-2"><div class = "amount">{{ product.amount }} </div>
        {{ product.Description }}
      </div>
      <div class="Area-3">
        <b-button size="sm" v-b-modal="`myModal-${product.ID}`" product_item = "'product'">
          More Details >> 
        </b-button>
        <b-modal :id="`myModal-${product.ID}`" >
          <h1> {{ product.Name }} </h1>
          <h3> {{ product.Description }} </h3>
        </b-modal>
      </div>
      <div class="Area-4">
        <br><button>Buy</button>
      </div>
    </div>
  </div>
</div>

For an example, check out this pen: https://codepen.io/Hiws/pen/qBWJjOZ?editors=1010

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

Finding and removing an element using Jquery

$.ajax({ type: "GET", url: "ajax/getLinks.php?url=" + thisArticleUrl }).done(function (data) { var extractedContent = $(data).find("#content > div > div.entry.clearfix"); extractedContent.find("#content > di ...

Having issues with reading files in PHP using AJAX? Explore alternative methods for downloading files seamlessly

I need to store a value in a txt file and allow the user to download it. Currently, the value is successfully written to the txt file, but the readfile function does not execute, preventing the download from starting. The PHP code is on the same page as ...

Is it necessary to create event objects before setting event handlers in Leaflet JS?

I'm currently working on creating event handlers that respond to the success of the location() method in the leaflet JavaScript map class Here is my current implementation: function initializeMap() { var map = L.map('map').locate({setV ...

What could be causing the issue when the selected option is being changed and the condition does not work

Whenever the selection in a select element is changed, the corresponding text should also change. Check out this Fiddle here. (function($) { 'use strict'; function updateResultText() { var s1_is_1 = $("#s1").value === '1', ...

Ways to display certain JSON elements

I'm attempting to retrieve a specific part of a JSON file through AJAX and display it in an HTML div. I only want to show a certain object, like the temperature. Here is the AJAX code: $(function () { $.ajax({ 'url': 'http://ap ...

Injecting an attribute with the forbidden character "@" into the Document Object Model (DOM

Scenario I find myself needing to update some existing HTML using JavaScript, but I'm limited in that the server side is out of my control. This means that any changes must be made client-side only without altering the original HTML document. To acc ...

Instructions for transforming rows into columns in JSON format

Looking to convert an array of JSON objects into a format where rows become columns and the values at the side become column values, similar to the crosstab function in PostgreSQL. The JSON data looks something like this: {"marketcode":"01","size":"8,5", ...

Guide on expanding the capabilities of IterableIterator in TypeScript

I am currently working on extending the functionality of Iterable by adding a where method, similar to C#'s Enumerable.where(). While it is straightforward to extend the Array prototype, I am encountering difficulties in figuring out how to extend an ...

Retrieve data from the page and component

Incorporated within my <Categories/> component are functionalities to interact with the main page using the fetch method to dispatch actions. The fetch functionality within the <Categories/> component operates smoothly as intended. A 're ...

Returning from a find operation in Node.js using Mongoose and MongoDB collections involves implementing a specific process

When attempting to find an element in a MongoDB collection using Mongoose in Test.js, the console.log is not being executed. Within Test.js, the console.log is failing to display the data retrieved from the MongoDB collection. var model = require(' ...

Creating a tree structure from an array in JavaScript, including the parent id enclosed in brackets

Before dismissing this question as a duplicate, please listen to me. I am working with a json response in reactjs that looks like the following organisationUnits: [ { name: "0.Mzondo", id: "nW4j6JDVFGn", parent: { ...

Trigger a function from a Bootstrap modal

Here is a preview of my HTML code : <form action="form2_action.php" method="post"> <table> <tr> <td>First Name </td> <td>:</td> <td><input type="text" id="f ...

Toggle the on and off functionality of a button using ajax response for content display

I'm struggling to figure out why the button isn't working for me. I am familiar with how to enable and disable buttons using attr and prop. $(document).on("click", "#btn", function(){ $(this).html("Sending..."); $(this).prop("disabl ...

Building a ReactJS application that displays an array of images with a distinct pop-up feature for each image

Having trouble creating unique popups for each image in React. I have a set of 20 images that should be clickable, with only one popup open at a time, each containing text and an image. Currently mapping out the images from an array. Looking for assistan ...

Trigger an event in jQuery when the focus moves away from a set of controls

Within a div, I have three textboxes and am looking for a way to trigger an event when focus leaves one of these inputs without transitioning to another one of the three. If the user is editing any of the three controls, the event should not be triggered. ...

Modifying state within useEffect while also including the redux value as a dependency array

I am facing an issue with my Redux array and the dependency array in my useEffect. The problem arises when I store the value of the Redux array in a variable using useSelector, which is then used as a dependency in my useEffect. The logic inside the useE ...

How can I extract the id of a clicked item and pass it to a different page with Jquery?

Facing an issue where the attribute value of a clicked href tag is not retained after browser redirection. Initially, when clicking on the href tag, the value is displayed correctly. However, upon being redirected to the peoplegallery_album, the id becomes ...

Tips for displaying complex JSON structures in VueJS

I want to extract this information from a JSON dataset <ol class="dd-list simple_with_drop vertical contract_main"> <li class="alert mar" data-id="1" data-name="Active" style=""> <div class="dd-handle state-main">Active<span cl ...

I noticed that my regular expression is functioning correctly on regex101, but for some reason, it's

My search works perfectly on regex101 using this link: https://regex101.com/r/z8JCpv/1 However, in my Node script, the third matched group array[2] is returning not only the matching text but also everything following it. An example line from the source ...

Using VueJS to assign data within a method function

Below is the HTML code that I have written: <div id="myApp"> <div class="items"> <div class="item" v-for="quiz in quizzes" :key="quiz.id"} <span>{{ quiz.question }}</span> <span v-if="selected[quiz. ...