Toggle the visibility of table rows using checkboxes

I'm working with checkboxes to toggle the visibility of specific rows in a table based on their content matching the selected checkbox values.

Checkboxes:

<input type='checkbox' name='foo1' value='foo1' v-model="selectedType"/> foo1 &nbsp;
<input type='checkbox' name='foo2' value='foo2' v-model="selectedType"/> foo2 &nbsp;
<input type='checkbox' name='bar1' value='bar1' v-model="selectedType"/> bar1 &nbsp;

I have structured a table using an object and the v-for directive:

<table>
    <template v-for="sampleItem in sampleObj">
        <tr>
           <td>{{sampleItem.item}}</td>
           <td>{{sampleItem.description}}</td>
        </tr>
    </template>
</table>

JS:

new Vue({
    data: {
        selectedType: [],
        sampleObj = [{'item': 'item1', 'description': 'foo1 blah'},
                     {'item': 'item2', 'description': 'foo2 vlah'},
                     {'item': 'item3', 'description': 'bar1 nlah'},
                     {'item': 'item4', 'description': 'bar2 clah'},
        ];
    }
});

The checkboxes start unchecked, displaying only the row with description 'bar2'. Toggling other checkboxes should make other rows visible based on partial matches in descriptions (not exact).

I wanted to use the v-if directive within the tag to check against selectedType values, but I am unsure how to implement this.

Pseudo-code:

<tr v-if="selectedType ~= /sampleItem.description/">
...
...
</tr> 

Any suggestions on how to achieve this functionality?

Answer №1

You have a specific set of conditions to be met for the v-if directive: the row should display if there is no checkbox that matches the description, and if there is a matching checkbox, it must be checked.

To handle this logic, I stored the checkbox values in the data section and created a method to perform the test. This method first checks if any checkbox value matches the description, and then verifies if the matched value is selected.

new Vue({
  el: '#app',
  data: {
    selectedType: [],
    sampleObj: [{
        'item': 'item1',
        'description': 'foo1 blah'
      },
      {
        'item': 'item2',
        'description': 'foo2 vlah'
      },
      {
        'item': 'item3',
        'description': 'bar1 nlah'
      },
      {
        'item': 'item4',
        'description': 'bar2 clah'
      },
    ],
    cbValues: ['foo1', 'foo2', 'bar1']
  },
  methods: {
    isVisible(row) {
      const matchedValue = this.cbValues.find(v => row.description.indexOf(v) >= 0);

      if (!matchedValue) {
        return true;
      }
      return this.selectedType.includes(matchedValue);
    }
  }
});
td {
  border: thin solid black;
}
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
  <div v-for="val in cbValues">
    <label>
      <input type='checkbox' :value='val' v-model="selectedType"> 
      {{val}}
    </label>
  </div>
  <table>
    <template v-for="sampleItem in sampleObj">
        <tr v-if="isVisible(sampleItem)">
           <td>{{sampleItem.item}}</td>
           <td>{{sampleItem.description}}</td>
        </tr>
    </template>
  </table>
</div>

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

What is the best way to create an animation where every letter in a word transitions to a different

Is there a way to animate a word so that each letter changes color within a range of 7 colors, with all letters displaying different colors simultaneously in an infinite loop? <div class="box"> <h1 class="logo animate__animated an ...

Tips for refreshing a page in Vue.js

I am facing an issue with updating a table on my page after deleting a row. Each row in the table has a delete button and I have tried using window.location.reload() but it didn't work. </va-card> <br/> <va-card > ...

Is it possible for the frontend and backend to use a shared package.json file?

Currently, I am working on a small personal project that is housed in a single repository. The backend consists of a Node.js server, while the frontend is built using Vue.js. I am looking to have both components share the same package.json file. The mai ...

Discover the best way to integrate your checkbox with your Jquery capabilities!

I am having trouble getting my 3 checkboxes to interact with the JQuery button I created. The goal is for the user to be able to select an option, and when the button is clicked, the selected options should download as a CSV file from my feeds. Below is th ...

Customizing the DatePicker with a unique button in material-ui

For my current project, I am utilizing a Datepicker component. I am looking to incorporate a custom information button in the upper right corner of the calendar layout, similar to the example image provided below: https://i.stack.imgur.com/fHMbn.png Unfo ...

Arranging objects in an array using jQuery for optimal organization

How can I rearrange the items based on their 'name' property? staticdata.items = [ {id: '0', 'name': 'ABC'}, {id: '0', 'name': 'XYZ'}, {id: '0', 'name': ' ...

Obtain the content enclosed within parentheses using JavaScript

const str = "(c) (d)"; I need to separate the given string into an array The result should be [0] => 'c' [1] => 'd' ...

Attempting to flip the flow of marquee loop in javascript

I am currently modifying this code to create a left-to-right marquee instead of the original right-to-left one. However, after successfully changing the direction, the text no longer loops as it did originally. I'm stuck and can't seem to figure ...

What is the process for editing a JSON file and preserving the modifications?

I have a JSON file with a key (food_image) and I am looking to dynamically assign the index value in a loop to it, such as food_image0, food_image1 ... food_image{loop index}. After that, I aim to save this modified JSON file under a new name. All values ...

Can we include intricate items within a redux store?

As I delve into developing a React application with Redux, I encountered an unexpected scenario. At one point, we inserted a DOM element within the store, causing issues with the Redux extension that freezes when the action is triggered. Despite this compl ...

Tips for transforming code with the use of the then block in javascript, react, and cypress

In my code snippet below, I have several nested 'then' clauses. This code is used to test my JavaScript and React code with Cypress. { export const waitForItems = (retries, nrItems) => { cy.apiGetItems().then(items => { if(items ...

Fetching locales asynchronously in nuxt.js using i18n and axios: A step-by-step guide

I am facing an issue with getting the location asynchronously. Whenever I try to implement my code, it results in a "Maximum call stack size exceeded" error. How can I resolve this issue? Previously, I attempted to retrieve the location by using the axios ...

Adjust the formatDate function in the Material UI datepicker

I recently implemented the material-ui datepicker component with redux form and it's been working great. However, I have encountered a minor issue. Whenever I change the date, it displays in the input field as yyyy-mm-dd format. I would like it to app ...

Changing all object values to true with React useState

In a certain file, I have defined an object with the following structure: export const items = { first: false, second: false, third: false } Within a component, I am using this object as shown below: import { items } from 'file'; const [el ...

Ensure the initial value in the dropdown menu is automatically set to the first value in VueJs

How can I set the first value of my time object as the default value for my dropdown in Vue? I want the first value to be pre-selected when a user enters the website, but currently only display the value without actually selecting it. time Object:- { &quo ...

Unlocking the power of python with web2py by tapping into html form values

I'm working on a project using web2py and need to incorporate ajax/javascript with a form. Currently, when a user selects an option in the departure box, the arrival box appears. However, I'm unsure of how to filter the list of arrival options ba ...

What should I do to resolve the issue of ajax failing to update data randomly?

This script is designed to take the value entered into an HTML form and send it to the ../Resources/BugReport.php file. The data is then inserted into a database in that file, and the table in the ../Resources/BugDisplay.php file displays the information f ...

How can I configure Express to act as a pass-through proxy server?

How can I set up an express server to act as a proxy? Requirements: Support for both http and https Ability to function behind a corporate proxy Option to provide custom content for specific URLs I have experimented with various modules such as http-pr ...

When is it necessary to use JSON.parse(JSON.stringify()) with a Buffer object?

I am currently working with Buffer objects in my existing code. let dataObject = JSON.parse(JSON.stringify(data)); At first glance, it seems like the above code is redundant and doesn't achieve much. However, replacing it with: let dataObject = data; ...

Command handler that dynamically utilizes both shared and separate commands

Currently, I am in the process of setting up a command handler for multiple channels on Twitch. To organize the commands, I have them divided into specific folders for each user and generic ones. Accessing these commands is done by using a map(). My goal i ...