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

How can Vue listen for a Vuex commit?

Is there a method to detect when a Vuex commit occurs without having to monitor specific property changes associated with the commit? Simply knowing if a commit has taken place? I am working on a Filter component that I plan to include in an NPM package. ...

Unable to access object key data from JSON-SERVER

I am currently attempting to send a GET request to json-server in order to retrieve data from a nested object. However, the response I am receiving is empty instead of containing the desired data key. After thoroughly reviewing the documentation, I could ...

What is the best way to create a delay so that it only appears after 16 seconds have elapsed?

Is there a way to delay the appearance of the sliding box until 16 seconds have passed? <script type="text/javascript"> $(function() { $(window).scroll(function(){ var distanceTop = $('#last').offset().top - $(window).height(); ...

Transfer the information on the onClick event to the loop's function

When creating my component within the parent component, I follow this approach: renderRow(row){ var Buttons = new Array(this.props.w) for (var i = 0; i < this.props.w; i++) { var thisButton=<FieldButton handler={this.actionFunction} key={&ap ...

Display PDF file retrieved from the server using javascript

I am currently working on a web application using JavaScript, jQuery, and Node.js. I need to receive a PDF file from the server and display it in a new browser window. While I believe I have successfully received the file on the client side (the window sh ...

display dynamic graphs using json data from a php backend

I'm having trouble displaying a graph using JSON data in Highcharts. Here is a sample of what I need: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/column-rotated-labels/ The file values ...

The jQuery script tag fails to recognize click events once dynamically loaded with the load event

Hey there, I recently utilized this script in a SAP WebDynpro setup to dynamically load and employ jQuery. The onload event of the script tag is functioning well as I can select the text of the focused element. However, I am facing issues with registering ...

Storing cookies is not supported when using jQuery for authentication with Passport.JS

My software setup includes an Electron app for the frontend and a Node backend. After clicking the login button, the app sends an Ajax POST request to the backend, which confirms successful authentication. However, when checking if the user is authentica ...

Learn how to dynamically insert input data into a table based on a specific ID in React JS!

[Help needed! I am trying to store the marks, id, and name values of each cell in objects of an array. However, I am not getting the correct answer. Can someone guide me on how to properly store the marks and id of each cell in objects of an array? const [ ...

Bypass ajax request with the use of a returned promise

I've come across a scenario where I have a function within a class that is designed to return a promise for deleting an item. Here's what the function looks like: function Delete(){ // if(this.id == ""){ // return ?; // } ...

Utilizing ng-href in Angular.js Template: A Guide

I am attempting to develop a simple Single Page Application (SPA) with just one index.html file that includes templates. However, I encountered an issue with the ng-href directive: <a ng-href="#/myPage">myPage</a> This works fine in index.h ...

Steps to submit a JavaScript-generated output as the value in a form input field

I'm facing an issue that seems basic, but I can't seem to figure it out. I'm trying to create a binary string representing the 12 months of the year using 12 checkboxes: const checkboxes = [...document.querySelectorAll('input[type=check ...

Observing a global object's attribute in Angular JS

Imagine you have an object in the global scope (yes, I know it's not ideal but just for demonstration purposes) and you wish to monitor a property of that object using Angular JS. var person = { name: 'John Doe' }; var app = angular.mod ...

Steps for retrieving a route parameter

Here is a sample configuration of my Vue router: export default new VueRouter({ mode: 'history', routes: [ /** * Authentication */ { name: 'login', path: '/', ...

Having trouble updating Vuejs array with new values

Currently, I am facing an issue with the template code for my survey builder. I am successfully receiving responses from the server, but the addAnotherQuestion value is not updating as expected. Despite trying various approaches, I have been unable to reso ...

When trying to load a php page2 into page1 via ajax, the Javascript code fails to execute

Currently, I am in the process of learning PHP and JavaScript. I have encountered a particular issue with a webpage setup. Let's say I have a page called page1 which consists of two input fields and a button labeled 'Go'. Upon clicking the & ...

Incorporate the AngularJS controller into your JavaScript code

I am facing an issue with my jQuery UI dialog that contains a dynamic <select> populated with Angular and AJAX. The problem is that the AngularJS script still runs even when the dialog is not visible. To solve this, I added a condition to stop the s ...

"Resetting the state of a form in AngularJS2: A step-by

Looking to reset the form state from dirty/touched in angular? I am currently delving into the world of angular2 and working on a form with validation. In my journey, I came across this code snippet: <form *ngIf="booleanFlag">..</form> This ...

What is the most effective way to determine if a statement is either false or undefined?

What is the most effective way to determine if a statement is not true or undefined, sometimes without necessarily being a boolean? I am attempting to improve this code. var result = 'sometimes the result is undefined'; if (result === false || ...

What are the most effective techniques for combining Vue.JS and Node.js backends into a single Heroku container?

I came across an interesting blog post today that discusses a method for deploying React applications. The author begins with a Node project and then creates a React project within a subfolder, along with some proxy configuration. About 10 days ago, I did ...