Switching between rows in a table once information has been added to an array | Vue

I'm currently working on creating a table with rows that toggle when a 'View' button is clicked. The table is generated using a for loop for an array. I've successfully implemented the toggling functionality for preloaded data, but encountering issues when pushing new data to the array.

Any suggestions on how to make the rows toggle correctly when clicking 'View'?

Thank you in advance!

For reference, here is the link to the JSBin: JSBin

Below is the code snippet:

HTML

<div id="app">
    <button type="button" class="btn btn-primary" @click="sites.push( {
        sku: '1005',
        purchasePrice: 4.50
      })">Add Data</button>

          <div class="table-wrapper">
            <table class="table table-hovered">
              <thead>
                <tr>
                  <th>SKU</th>
                  <th>Purchase Price</th>
                </tr>
              </thead>
              <tbody>
                <template v-for="item in sites" >
                  <tr>
                    <th>{{ item.sku }}</th>
                    <th> {{ item.purchasePrice }}</th>
                    <th id="toggle" @click="addEvent($event, item)">
                      View
                    </th>
                  </tr>
                  <template v-if="item.showTab">
                    <tr>
                      <th class="subCol subTable" colspan="6">
                         Content
                      </th>
                    </tr>
                  </template>
                </template>

              </tbody>
            </table>
          </div>
  </div>

Vue JavaScript

new Vue({
  el: '#app',
  data: {
        sites: [
      {
        sku: "10001",
        purchasePrice: "4.50",
        showTab: false,

      },
      {
        sku: "10002",
        purchasePrice: "4.50",
        showTab: false,
      },
      {
        sku: "10003",
        purchasePrice: "4.50",
        showTab: false,
      }
    ],
    newData: [],
    },
    methods: {
     addEvent(event, item, type, target) {
      this.newData = [];
      for (let i = 0; i < this.sites.length; i++) {
        if (event.target.id == "toggle") {
          item.showTab = !item.showTab;
        }
      }
      this.newData.push(this.sites);
    },
    }
});

Answer №1

Oops! It seems there are a few small errors that may have caused your result to be unexpected.

Firstly, it looks like the showTab property is missing when you add an item to your array.

Try replacing this section of code:

<button type="button" class="btn btn-primary" @click="sites.push( {
    sku: '1005',
    purchasePrice: 4.50
  })">
  Add Data
</button>

With this updated version :

<button type="button" class="btn btn-primary" @click="sites.push( {
    sku: '1005',
    purchasePrice: 4.50,
    showTab: false
  })">
  Add Data
</button>

Additionally, it appears that when you trigger the toggle, you are updating all elements in the array instead of just toggling one specific element. This happens because every element meets the condition if (event.target.id == "toggle").

To properly achieve toggling only one element, you should replace the following code:

addEvent(event, item, type, target) {
   this.newData = [];
   for (let i = 0; i < this.sites.length; i++) {
     if (event.target.id == "toggle") {
       item.showTab = !item.showTab;
     }
   }
   this.newData.push(this.sites);
}

With the revised snippet below :

addEvent(event, item, type, target) { // Consider removing any unused arguments
   item.showTab = !item.showTab;
}

You could even directly update the item's toggle mode in the HTML like this :

<th id="toggle" @click="item.showTab = !item.showTab">
  View
</th>

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

Zooming on a webpage is causing problems

One issue I'm facing is with the elements on my page acting strange when I zoom in and out. Everything seems to be working fine except for a container div that should overlay a color over the image background. When I zoom in or switch to mobile view, ...

Securing a route using a referrer in Node.js: Best practices

Within my node.js application, I am looking to secure a specific route so that users can only access the page /post if they are coming from /blog. If the user accesses the route from any other source, they should be redirected to /. I have implemented the ...

Is it possible to directly update the label text in AngularJS from the view itself?

I found the following code snippet in my HTML <span ng-class="newProvider ? 'newProvider' : ''" class="help-block"> {{ 'new-product.provider.helper' | locate }} </span> Whenever newProvider is se ...

Inaccurate data saved to a cookie

I attempted to assign a string from PHP to a cookie and retrieve the value of that cookie using JavaScript. Take a look at my code snippet: <php $date=date('Y',time()); //assume it is 2017 setcookie("Year", $date, time() + 3600, "/"); ?> ...

What in the world is going on with this code snippet? I'm completely stumped on how to fix this problem

Attempting to generate a custom element with unique properties function y(){ var g=document.createElement("div"); this.label="elephant"; return g; } y.prototype.customFunction=function(){ alert(arguments[0]+this.label); }; var b=new y(); b ...

Implementing a Basic jQuery Animation: How to Easily Display or Conceal DIV Elements Using fadeIn and fadeOut

SCENARIO: Include 2 links, MY INFO and LOG IN, within a list of ul, li elements. Hovering over one link should display a box with a form inside using the fadeIn animation. The other link should show a button in a box with a fadeIn animation when hovered o ...

What is the process for logging in or authenticating before running tests with pa11y-ci?

Is there a way to authenticate users and test pages using pa11y-ci? When running pa11y-ci, I typically use this command: pa11y-ci --sitemap http://www.example.com/sitemap.xml --sitemap-find https --sitemap-replace http I came across some helpful informa ...

What seems to be causing the malfunction in my child component's functionality?

When passing data to child components using props, sometimes it may seem like the tag isn't working properly. For example, in this case, why isn't 'hello' being printed out? Here is the code snippet: <div id="app"> <child m ...

Repetitive bouncing in a trampoline leads to the error message "Call stack has reached maximum size"

I have been delving into the world of blockchain and experimenting with a simple implementation of "proof of work". Proof of work: export function mineBlock(difficulty: number, block) { const prefix = Array(difficulty + 1).join("0"); function mine(b ...

Puppeteer encountered an error when trying to evaluate the script: ReferenceError: TABLE_ROW_SELECTOR was not defined

https://i.stack.imgur.com/PJYUf.jpg Recently, I started exploring pupeteer and node while using vscode. My goal is to log into a website and scrape a table. So far, this is what I have: (async () => { const browser = await puppeteer.launch({ headle ...

Transmitting intricate Javascript Array to ASP.NET Controller Function

I am facing an issue with sending a complex JavaScript array to my asp.net mvc6 controller method. I have tried two different methods to pass the data, but neither seem to be working for me. public IActionResult TakeComplexArray(IList<ComplexArrayInfo ...

The native javascript modal fails to appear

I'm attempting to implement the functionality from this Codepen demo into my project. I've copied over the HTML, CSS, and JavaScript code: <!DOCTYPE HTML> <html> <head> <script> var dialog = docume ...

Saving real-time information to MongoDB with Node.js

What is the best way to use JSON.stringify and send it to my mongoDB Database? For instance: import express from 'express'; let data_record = JSON.stringify({**any content**}) This snippet of code will automatically fetch data every 60 second ...

Troubleshooting issues with the controller functionality in AngularJS

The following code is not producing the expected output of 'Hello, World' output: {{ greetings.text }}, world Could someone please assist me in determining why it is not displaying 'hello, world' as intended <!doctype html> ...

Maintaining a consistent style input until it is modified

I'm currently dealing with this code (continuing from a previous question): input[type=submit]:focus { background-color: yellow; outline: none; } The issue I'm facing is that when I click anywhere else on the screen, the background color go ...

Preventing Prepend Scroll: Tips and Tricks

Adding extra content to the top of the body can be frustrating, especially if it pushes everything down as you're trying to read. Is there a way to smoothly prepend this additional content without shifting the page layout, so that it seamlessly appear ...

Guide on launching a mobile application upon clicking a button in a mobile browser (with the assistance of JavaScript/React) [Utilizing Deep Linking]

My goal is to create a functionality where, on a mobile browser, when the user clicks on a button: If the app is already installed on the user's mobile device, it should open up. If the app is not yet installed, I aim to redirect the user to the appr ...

Utilizing a dynamically created table to calculate the number of neighbors

I have a challenge where I want to create a minesweeper game with numbers indicating how many bombs are nearby. For example, if there are two bombs next to each other and I click on a cell adjacent to them, it should display the number 2. Likewise, if ther ...

Create dynamic elements in Vue.js components based on an object

I'm currently working on a component that will display elements within VueJs virtual dom using Vuex state. However, I have encountered an error that I am unable to comprehend and resolve: Avoid using observed data object as vnode data: {"class":"b ...

show data pulled from localStorage

I'm struggling to figure out how to use localStorage for the first time, specifically in storing an array of objects and displaying that information even after page refresh. Currently, I can see that it is being stored but not displayed. const book ...