What is the best way to display an array of object values related to checkboxes using Vue.js?

I am attempting to display the array of objects associated with the checkbox, for example, when the checkbox tree is checked, it should print the trees array. If no checkboxes are selected, all arrays should be printed. I am looking for the simplest way to accomplish this.

Below is my code:

<template>
  <main>
    <section>
      <div>
        <input id="boundingBox" type="checkbox" value="boundingBoxes" v-model="boundingBoxes">
        <label for="boundingBox"> i1 </label>

        <input id="tree" type="checkbox" value="trees" v-model="trees">
        <label for="tree"> i2 </label>

        <input id="last" type="checkbox" value="cars" v-model="cars">
        <label for="last"> i3 </label>
      </div>
      
      <div class="divWhereTheValuesArePrinted">
        <!-- print selected checkboxes -->
        <!-- if no checkboxes are selected, print all -->
      </div>
    </section>
  </main>
</template>
<script>
  export default {
    data() {
      return {
        boundingBoxes: [
          {
            name: "bounding box",
            color: "red"
          },
          {
            name: "bounding box",
            color: "orange"
          }
        ],
        trees: [
          {
            name: "tree",
            color: "green"
          },
          {
            name: "tree",
            color: "red"
          },
          {
            name: "tree",
            color: "yellow"
          }
        ],
        cars: [
          {
            name: "car",
            color: "black"
          },
          {
            name: "car",
            color: "blue"
          },
          {
            name: "car",
            color: "brown"
          }
        ]
      }
    },
  }
</script>

The script contains the arrays to be printed.
The checkboxes v-model="" correspond to the array names.
The values will be displayed below the div containing the inputs and labels.

Answer №1

Here is a solution that I believe aligns with your expectations:

Code snippet for my Vue component:

<template>
  <main>
    <section>
      <div>
        <input id="boundingBox" @change="myFunction" type="checkbox" value="boundingBoxes" v-model="showArr">
        <label for="boundingBox"> Option 1 </label>

        <input id="tree" type="checkbox" @change="myFunction" value="trees" v-model="showArr">
        <label for="tree"> Option 2 </label>

        <input id="last" type="checkbox" @change="myFunction" value="cars" v-model="showArr">
        <label for="last"> Option 3 </label>
      </div>

      <div class="divWhereTheValuesArePrinted">
        <!-- Values selected from checkboxes are printed here -->
        <!-- If no checkboxes are selected, all options are displayed -->
        <div v-for="item in finalArr">
          {{ item }}
        </div>
      </div>
    </section>
  </main>
</template>

I have tested this code using Vue version 3.2.31 since you did not specify the exact version you are working with. However, it should also function correctly on other versions of Vue.

Answer №2

<div>
    <input id="check1" type="checkbox" value="option1" @click="handleClick(0)" v-model="values[0]">
    <label for="check1"> Checkbox 1 </label>

    <input id="check2" type="checkbox" value="option2" @click="handleClick(1)" v-model="values[1]">
    <label for="check2"> Checkbox 2 </label>

    <input id="check3" type="checkbox" value="option3" @click="handleClick(2)" v-model="values[2]">
    <label for="check3"> Checkbox 3 </label>
</div>
<div class="contentArea">
    <!-- Display selected checkboxes -->
    <div v-if="selectedKey !== null">{{ this[selectedKey] }}</div>
    <!-- If no checkbox is selected, display all options -->
    <div v-else>
        {{ option1 }}
        {{ option2 }}
        {{ option3 }}
    </div>
</div>

{
    data(){
        selectedKey: null,
        values: [false, false, false],
        valueKeys: ['option1', 'option2', 'option3'],
    },
    methods:{
        handleClick(index) {
            this.values = this.values.map((val, ind) => {
                if (index !== ind) return false;
                this.selectedKey = !val ? this.valueKeys[index] : null;
                return !val;
            });
        },
    }
}

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

jQuery is in a constant state of indecision when it comes to determining the best way to manage buttons

A straightforward scenario. When a checkbox is checked, it activates a disabled button. Unchecking the box disables the button again. Sample Code: jQuery -> $('#subscribe_button').attr('disabled','disabled') $("[name= ...

Node.js - Synchronize asynchronous calls to ensure coordinated execution in code

I am trying to figure out how to make a for loop with an async function wait until all the async functions called within it are finished before allowing the code to continue. In my scenario, I have a variable "bar" that contains a JSON array with other ne ...

Alter the color of the text within the `<li>` element when it is clicked on

Here is a list of variables and functions: <ul id="list"> <li id="g_commondata" value="g_commondata.html"> <a onclick="setPictureFileName(document.getElementById('g_commondata').getAttribute('value'))">Variable : ...

jQuery technique for loading images

Here is the issue at hand: I am attempting to utilize jQuery to accelerate image loading on my webpage. To achieve this, I have a code snippet specifying an initial image that should be replaced with another image once the page has finished loading. < ...

Using Cordova for mobile applications to play local video files

Our iOS app, developed using PhoneGap / Cordova 4.3.0, loads an external website directly utilizing <content src="http://example.com/foo" /> in the config.xml file. All functionality resides within this website, eliminating the need for local HTML or ...

JavaScript Oddity - Array Increment Trick

What is the reason behind ++[[]][0] == 1 While trying to do ++[] leads to an error? Shouldn't they produce the same result? My understanding is that the first example performs an index-read on the array, resulting in an array within an array. The ...

Using jQuery to obtain the object context while inside a callback function

Suppose I have the following object defined: var myObj = function(){ this.hello = "Hello,"; } myObj.prototype.sayHello = function(){ var persons = {"Jim", "Joe", "Doe","John"}; $.each(persons, function(i, person){ console.log(this.h ...

Error message: The Symfony ObjectNormalizer is encountering an empty property path

Currently, I am facing a challenge in serializing a complex object to return it as a response in json using Symfony Serializer. The object in question is as follows: /** * @Doctrine\Entity * @Doctrine\Table(name="Fichiers") */ class File{ /** * ...

Testing Two Pages in an App Sequentially with Protractor and Angular

I want to execute Protractor tests on two distinct pages in my Angular app: /dashboard and /articles. The challenge lies in the fact that I need to manually log into the application. Currently, this is how it's set up: var LoginPage = function() { ...

What is the most effective way to communicate to my client that attempting to conceal the browser toolbar is an ill-advised decision?

One of my clients has a friend who claims to be conducting 'security testing' and insists that the PHP Zend Framework application I developed for them should implement certain browser-side features: hide the location bar, toolbar, bookmarks, me ...

Ways to apply the .not selector efficiently in jQuery

I have a situation with two separate divs, one named task1 and the other named task2. Each of these tasks contains panels with various names. Within task2, there is a duplicate name (Greg), who also belongs to the duplicate class. I'm trying to figure ...

Tips for creating a scale animation using HTML5 Canvas

I am currently developing a canvas whiteboard tool and I have reached the stage where I am focusing on implementing the Zoom In and Zoom Out feature. While the functionality is working fine, I would like to enhance it with smooth animations for scaling. H ...

Tips for looping through nested JSON data in Google Sheets

In my attempt to iterate through the nested "line_items" element in a JSON response triggered by a post event, I aim to populate a Google Sheets spreadsheet using Google Apps Script. My objective is to write the elements within each "line_item" into new ro ...

Safari has no issues running Javascript, but other browsers are encountering failures

I am facing an issue where the code is working on Safari but failing on other browsers, and I can't figure out why. You can find the html part and the main javascript part. The main issue at hand is: When executing the function downloadurl(url, fun ...

What is the best way to centrally align a Card while keeping the text left-aligned?

New to coding and need some guidance. I'm attempting to create a card that is not the full width of the window. I have specified a cardStyle as shown below. cardStyle:{ width: '95vw' align? : 'center?' textAlign? : &a ...

Angular 14 is experiencing issues with NgRx Store failing to properly recognize the payload

The issue lies in TypeScript not recognizing action.payload.index as a valid property. I am unsure how to resolve this problem and make the 'index' visible in my project. shopping-list.actions.ts import {Action} from "@ngrx/store"; im ...

Server-side rendering or updating of React elements

One issue I am facing in my React app is that while all components can update themselves through the browser, a specific module called jenkins-api only functions when called server side. To retrieve the data and pass it into my template, I have utilized th ...

Creating variable assignments based on object properties

I am facing a dilemma with a simple object that contains constants. { KEY1: "value1", KEY2: "value2" } I am looking for a way to make these constants accessible globally. Currently, I have to use Config.KEY1 to access the values globally, but I w ...

Is it illegal to escape quotes when using an image source attribute and onerror event in HTML: `<img src="x" onerror="alert("hello")" />`?

Experimenting with escape characters has been a fascinating experience for me. <img src="x" onerror=alert('hello'); /> <img src="x" onerror="alert(\"hello\")" /> The second code snippet triggers an illegal character error ...

Using jQuery sortable with the overflow property set to hidden to sort items between two lists

I need help with a jQuery sortable feature where I have two lists and can move items between them: $( '#productsList, #orderList' ) .sortable({connectWith: '.containerDiv'}) .disableSelection(); My issue arises when I try to implement ...