Change the background color of a particular row in a table using Vue.js to be red

I am having an issue with a regular table - when I click on a specific row, I want only that row to turn red.

Below is the code snippet that I have attempted:

<tr role="row" v-for="(proxy, key) in this.ProxiesList" @click.prevent="this.BackGroundRed = !this.BackGroundRed" v-bind:style="[this.BackGroundRed ? 'background-color:red' : '']">

<td class="sorting_1"><a href="#"><span class="inv-number">{{ key + 1 }}</span></a></td>
<td>
<div class="d-flex">
<div class="usr-img-frame mr-2 rounded-circle">
<img alt="avatar" class="img-fluid rounded-circle" src="/img/logo-mini.png">
</div>
<p class="align-self-center mb-0 user-name"> {{ proxy.ProxyIP }} </p>
</div>
</td>
</tr>

VUEJS

data() {
    return {
        BackGroundRed: false
    }
},

However, the issue persists as clicking on a row turns all rows red!

Answer №1

If you're looking to implement a functionality like the one described below in your project, you can use the code snippet provided (avoid using this in template):

new Vue({
  el: '#demo',
  data() {
    return {
      backgroundRed: null,
      ProxiesList: [{id:1, ProxyIP:1}, {id:2, ProxyIP:2}, {id:3, ProxyIP:3}, {id:4, ProxyIP:4}]
    }
  },
  methods: {
    setBg(id) {
      this.backgroundRed = id
    }
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <table>
    <tr role="row" v-for="(proxy, key) in ProxiesList" @click="setBg(key)" :style="backgroundRed === key ? 'background-color:red' : ''">
      <td class="sorting_1"><a href="#"><span class="inv-number">{{ key + 1 }}</span></a></td>
      <td>
        <div class="d-flex">
          <div class="usr-img-frame mr-2 rounded-circle">
            <img alt="avatar" class="img-fluid rounded-circle" src="/img/logo-mini.png">
          </div>
          <p class="align-self-center mb-0 user-name"> {{ proxy.ProxyIP }} </p>
        </div>
      </td>
    </tr>
  </table>
</div>

Answer №2

If the variable BackGroundRed is set to true, all the <tr> elements in your code will have a red background color.

To address this issue, consider creating an array to store selected rows and add the row identifier to it upon selection. Then, you can easily check if the current row identifier is in the array of selected rows and apply the red background accordingly.

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

Top Method for Initiating AJAX Request on WebForms Page

Looking for the best way to execute an AJAX call in a WebForms application? While ASP.NET AJAX components are an option, some may find them a bit heavy compared to the cleaner approach in MVC. Page Methods can be used, but they require static methods ...

What is the best way to include keys in my JSON data, rather than just values?

I've encountered an issue with the PrimeVue datatable I created, as it is only showing empty rows. After investigating, I believe the problem lies in my JSON data structure, where the fields do not have keys. What modifications should be made to stan ...

Combining two objects by id and grouping identical key-value pairs together

var routePlan = [ { "id" : 1, "farmerName" : "Farmer1", "farmerId" : 1 }, { "id" : 2, "farmerName" : "Farmer2", "farmerId" : 2 }, { "id" : 1, "farmerName" : "Farm ...

Troubleshooting problem in AngularJS: $http request causing DOM to not update when calling jQuery function

I'm encountering an issue where the DOM is not updating when I make a $http request in a jQuery function call. Please take a look at the Plunker In my code script.js, for testing purposes, I have $scope.components defined both globally and within a ...

Is npm create-react-app giving you trouble?

When attempting to create a React app using the command npm create-react-app appname, the tool would just return me to the same line to input more code. I also gave npx a try, but encountered some errors in the process. See this screenshot for reference: ...

Formatting dates in a C# MVC application after parsing JSON

I am working on an MVC application that retrieves data from a SQL database and passes it to a view. One of the views contains a Kendo grid that displays the data, including a date column. The date data is stored in the SQL database as DateTime, while the m ...

Parsley JS - Personalized Validation for Ensuring selected Items meet Minimum Value Requirements

Is it possible to validate a form so that at least 5 select boxes are set to Yes? If there are fewer than 5, the form should not submit and display an error message. I believe a custom validator is needed for this task. To see a complete example, check ou ...

Arranging Material UI tabs on both sides

I'm currently working with Material UI tabs and I'm trying to achieve a layout where some tabs are positioned to the left and others to the right. For instance, if I have 5 tabs, I want 3 on the left and 2 on the right. I've tried placing th ...

Is it possible to redirect a URL with a readyState of 4?

Is it possible to redirect to a page when the readyState is equal to 4? //load the send form if (sendRequest) { sendRequest.open("POST", urlRequest, true); sendRequest.setRequestHeader("Content-Type", "application/x-www-form-urlenc ...

Using jQuery to add a class to an input option if its value exists in an array

Looking for a way to dynamically add a class to select option values by comparing them with an array received from an ajax call. HTML <select id="my_id"> <option value="1">1</option> <option value="2">2</option> ...

Integrate JavaScript date into the gulp-rev workflow

I have been encountering an issue while using the gulp-rev plugin to add a revision of my app/html page generated by the Yeomann webapp generator. My workflow involves zipping the app and then adding a revision, but I am having trouble replacing the hash t ...

Updating the image source URL dynamically inside a division within a script using JavaScript

I'm attempting to insert a dynamic URL within an img src tag. Below is my HTML and Script code. When a tab is clicked, a GET HTTP Method is called, which responds with an image URL. I want to use this image URL in the img src field. HTML Code ...

Looking to eliminate the bullet point next to the labels on a highcharts graph?

I have implemented a Highcharts solid gauge in my project, and you can view a sample image https://i.stack.imgur.com/QQQFn.png However, I am facing an issue where unwanted grey bullets are appearing in the test environment but not locally. I have checked ...

The error message "Unexpected token < in JSON at position 0" is indicating a SyntaxError in the

I am facing an issue with the API on this specific page. Although the API is working fine on other pages, it seems to be encountering a problem here. I'm not sure what's causing the issue. Below is the code snippet: export async function getStati ...

Tips on effectively centering a wide div

After much experimentation, this is what I came up with: (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en ...

Guidelines for sending data to child components using Vue Router

I'm currently working on a Vue component that includes Navigation and layout features and relies on a bus to communicate with its sub-components. The bus is passed down as a prop to the sub components, which then utilize $emit for communication. expo ...

The TextField is currently unable to be edited because of an Uncaught TypeError stating it is not iterable

Currently, I am fetching data from an API and updating TextFields with it for display. My goal is to allow users to edit the data shown in these TextFields, but I keep encountering a Uncaught TypeError: prev.fields is not iterable error whenever I attempt ...

Exploring Javascript/JQuery parameters based on data types

I'm a bit confused about whether the title accurately reflects my question. I need help understanding how jQuery deals with functions that are called with different argument combinations, such as ("Some String", true, function(){}) and ("Some String", ...

Retrieve the concealed method's name within the immediately invoked function expression (IIFE

This Meteor sever code has a private method called printFuncName within an IIFE. However, when this method is invoked from a public method, it results in the following error: TypeError: Cannot read property 'name' of null I am curious to unde ...

What is the best way to display a list of items in Vue JS while maintaining the

Looking to display my Vue.js list in reverse order using v-for without altering the original object. The default HTML list displays from top to bottom, but I want to append items from bottom to top on the DOM. Telegram web messages list achieves this wit ...