Click on a table cell in Vue to display its corresponding data in a modal

I have successfully implemented a modal in my Vue component that works well with static text inside it, confirming its functionality.

However, when attempting to pass data from the table cell that is being clicked into the modal, I encountered an error stating that name is undefined.

What am I missing in my approach to passing data from each cell into the modal?

<div id="app">
  <table>
  <tbody>
    <tr>
      <td v-for="name in names"  @click="showDetailModal = true"></td>
      <td>@{{ name }}</td>
    </tr>
  </tbody>
  </table>


  <div class="modal-vue">
    <div class="overlay" v-if="showDetailModal" @click="showDetailModal = false"></div>

    <div class="modal" v-if="showDetailModal">
      <button class="close" @click="showDetailModal = false">x</button>
      <h3>@{{ name.age }}</h3>
    </div>
  </div>
</div>


new Vue({
  el: "#app",
  props: { 

  },
  data: {
    showDetailModal: false,
    names: [
      {
        "name":"Amy",
        "age":37
      },
      {
        "name":"James",
        "age":39
      }
    ]
  }
})

Answer №1

Add a new data property named currentItem and then set the clicked item to it when you click on the table row:

<div id="app">
  <table>
  <tbody>
    <tr>
      <td v-for="name in names"  @click="showModal(name )"></td>
      <td>@{{ name }}</td>
    </tr>
  </tbody>
  </table>


  <div class="modal-vue">
    <!-- overlay to help with readability of modal -->
    <div class="overlay" v-if="showDetailModal" @click="showDetailModal = false"></div>

    <!-- Modal for detail on table cell click event -->
    <div class="modal" v-if="showDetailModal">
      <button class="close" @click="showDetailModal = false">x</button>
      <h3>@{{ currentItem.age }}</h3>
    </div>
  </div>
</div>


new Vue({
  el: "#app",
  props: { 

  },
  data: {
    showDetailModal: false,
    names: [
      {
        "name":"Amy",
        "age":37
      },
      {
        "name":"James",
        "age":39
      }
    ],
    currentItem:{name:'',age:''}
  },
methods:{
  showModal(item){
     this.showDetailModal = true;
     this.currentItem=item
  }

}
})

Answer №2

The reason why the `name` is undefined is because it is only accessible inside the `v-for` loop.

Therefore, when a table cell is clicked, it is necessary to keep track of which user was clicked. This allows the modal to display the selected user based on that information.

The solution proposed by Boussadjra Brahim works well, although it could be improved by eliminating the `showDetailModal` data.


<div id="app">
  <table>
  <tbody>
    <tr>
      <td v-for="name in names"  @click="showModal(name )"></td>
      <td>@{{ name }}</td>
    </tr>
  </tbody>
  </table>


  <div class="modal-vue">
    <!-- overlay to improve modal readability -->
    <div class="overlay" v-if="currentItem" @click="currentItem = false"></div>

    <!-- Modal for displaying details on table cell click event -->
    <div class="modal" v-if="currentItem">
      <button class="close" @click="currentItem = false">x</button>
      <h3>@{{ currentItem.age }}</h3>
    </div>
  </div>
</div>


new Vue({
  el: "#app",
  props: { 

  },
  data: {
    names: [
      {
        "name":"Amy",
        "age":37
      },
      {
        "name":"James",
        "age":39
      }
    ],
    currentItem: false
  },
methods:{
  showModal(item){
     this.currentItem=item
  }

}
})


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

Sharing a collection of data fields

I am dealing with dynamic fields within a Bootstrap three form that is divided into tabs. Due to the removal of form tags in the modal, I have my fields set up outside. I can successfully post the values using jQuery attribute selectors like $("input[name ...

Tips on avoiding scrolling when toggling the mobile navigation bar:

While working on a website using HTML, CSS, and BS3, I have created a basic mobile navigation. However, I am facing an issue where I want to disable scrolling of the body when toggling the hamburger button. The problem arises when the menu is toggled on, ...

How can I adjust the font size of material-ui buttons while ensuring that they scale appropriately?

Having trouble adjusting the font sizes on Material-UI's RaisedButton for React and ensuring that the button scales properly along with it. <RaisedButton label={<span className="buttonText">Log in Here</span>} /> CSS: .buttonText ...

What is the reason for `change()` not being defined in the constructor? Is it supposed to be accessed through the `__proto__` link in `

Why is the change() method not defined in the constructor? Shouldn't it be accessed through the proto link in the p.proto? // The first change() is not defined, why? class Person { constructor() { console.log(this) console.log(this.__prot ...

Retrieve the scope object using angular.element and the $ID parameter

In order to transfer data from an angular application to scripts that operate outside of angular, I am seeking a solution since I cannot modify the code of the angular app. By utilizing Angular Batarang and NG-Inspector extensions in Chrome, I have identi ...

Extract images from dynamically loaded JavaScript website

I'm attempting to extract images from a webpage that is rendered using JS, but the picture links in the source code are incomplete. Here is where the images are located: <script language="javascript" type="text/javascript"> </script> < ...

Is the Expand All / Collapse All feature malfunctioning when used with a tree table?

I have been working on implementing the Expand All/Collapse All feature for a nested tree table, but unfortunately, I am not achieving the desired output. I referred to a related question on this topic which can be found here. You can also view the code on ...

Ways to combine and run the outcomes of several functions with Lodash

Imagine you have two distinct functions (or more) that take one argument from an executor and return the result object. Let's illustrate this with an example: const style_1 = theme => ({ header : { color : theme.primary } }) const sty ...

Issues arise when jQuery functions do not execute as expected within an "if" statement following

Recently, I delved into the realm of AJAX and embarked on a journey to learn its intricacies. Prior to seeking assistance here, I diligently scoured through past queries, such as this, but to no avail. Here is an excerpt from my code: $('.del'). ...

The function initFoodModel is missing and causing issues as it tries to read properties of undefined, specifically attempting to read 'findAll'

myWishlist.js const { setupFoodModel } = require("../../model/FoodModel"); const { setupWishlistModel } = require("../../model/myWishlistModel"); const setupMyWishlistModel = async () =\> { try { const sequelizeConnection = awai ...

Error occurred while retrieving JSON array using Jquery

var groupMembers = $.parseJSON(members); $.each(groupMembers, function (index, item) { $.ajax({ type: "POST", url: "'.base_url(" / panel / listNotifications ").'/'.$id.'/" + valueSelected, d ...

Possibility for using navigator.GetUserMedia in Internet Explorer

How can I access a webcam through JavaScript/jQuery? I have successfully opened the webcam in Chrome and Mozilla, but the navigator.GetUserMedia feature does not work in Internet Explorer. Is there a way to achieve this with JavaScript or jQuery in IE? ...

Error in GatsbyJS: Unable to retrieve data from property 'childImageFluid' due to undefined value

Currently tackling a Gatsby website, but running into an issue: "TypeError: Cannot read property 'childImageFluid' of undefined" Here's the code snippet from my Project.js file: import React from "react" import PropTypes from &quo ...

Symfony Form Validation through Ajax Request

Seeking a way to store form data with Symfony using an Ajax call to prevent browser refreshing. Additionally, I require the ability to retrieve and display field errors in response to the Ajax call without refreshing the page. I have a Symfony form setup ...

Expanding the Element prototype with TypeScript

Is there a corresponding TypeScript code to achieve the same functionality as the provided JavaScript snippet below? I am looking to extend the prototype of the HTML DOM element, but I'm struggling to write TypeScript code that accomplishes this with ...

Having trouble executing a Vue project as I encountered an error stating: "Module not found: '@vue/cli-plugin-babel'". To fix this, I proceeded to install the necessary dependencies by running the command: npm install

Error: The module '@vue/cli-plugin-babel' could not be found. Require stack: C:\Users\HP\AppData\Roaming\npm\node_modules@vue\cli-service\lib\Service.js C:\Users\HP\AppData\Roaming ...

propagate the previous state using a variable

Currently, I am in the process of refactoring a codebase but have hit a roadblock. My main aim is to update the state when the onChange event of a select box occurs. Specifically, the parameter searchCriteria in my handleFilterChange function is set to in ...

Place the Drawer element at the bottom of the menu

Is there a way to position the menu point at the bottom of the screen? It would be great if we could easily customize the style of the navigation options for each element. Check out my App Navigator below: const AppNavigator = createDrawerNavigator( ...

Finding All Initial Table Cells in jQuery

Is there a streamlined method for retrieving all td elements (cells) from every row within a specific table, or do I have to manually iterate through the collection myself? ...

Discovering if an ID already exists in a Firebase real-time database with React.js

https://i.sstatic.net/i1QVd.png Currently, I am engaged in a React inventory project. In order to avoid duplication when pushing data into the progress.json file, I need to ensure that the data is not already present by checking for the unique id associat ...