Implementing Vue Js checkboxes using dynamic JSON data

I have a product search page where users can filter based on selected category.

When a category is chosen, the API returns the following response:

  "customFields":{
     "select":{
        "brand":{"options":[ "nike", "adidas","puma"]},
        "colour":{"options":["black","grey","white"]
     },
     "range":{
        "price":{"options":["0","100","1000"]
     }
  }

The Select fields are checkboxes allowing for multiple selections, while the Range fields require users to select a minimum and maximum value.

To create the checkboxes, I have implemented the following code:

<div class="form-row" v-for="(selectField, index) in selectCustomFields">
    <div class="overflow-auto options-list" v-for="(value, name) in selectField.options">
        <label class="custom-control custom-checkbox mb-3">
            <input type="checkbox" class="custom-control-input" v-model="index" :value="value" @click="onChange($event)">
            <span class="custom-control-label">
                <span class="text-dark">{{ value }}</span>
            </span>
        </label>
   </div>
</div>

How can I retrieve the values of all checked options in termQualities?

Is there a way to create an array of checkboxes to store all selected values?

I am aiming for something similar to this example, with the only difference being that the sidebar filters change based on the product category.

Thanks!

Answer №1

new Vue({
      el : "#app",
      data : () => ({
        customFields : {
            select : {
                brand : {
                    options : ["nike","adidas","puma"]
                },
                colour : {
                    options : ["black","grey","white"]
                }
            },
            range : {
                price : {
                    options : [0,100,1000]
                }
            }
        },
        selected : null,
      }),
      methods : {
        initialize_selected(){
          var selected = {};
          for(var e in this.customFields){
            for(var f in this.customFields[e]){
              if(e=='range'){
                selected[f] = {min : null, max : null};
              }
              else{
                selected[f] = [];
              }
            }
          }
          this.selected = selected;
        }
      },
      mounted(){
        // Initialize data.selected based on filter fields once customfields are obtained from the server
        // Example: using axios 
        // this.$axios.get('/customfields')
        // .then(res=>{
        //   this.initialize_selected();
        // })
        this.initialize_selected();


        setTimeout(() => {
          console.clear();
        }, 1);
      }
    })
<div id="app">
    <!-- Display only after selected is initialized -->
    <div v-if="selected" v-for="(each, key) in customFields">
      <div v-if="key=='select'">
        <div v-for="(option, subkey) in each">
          Select {{subkey}}
          <p>
            <div v-for="optiondata in option['options']">
              <label for="optiondata">{{optiondata}}</label>
              <input type="checkbox" :id="optiondata" :value="optiondata" v-model="selected[subkey] ">
            </div>
          </p>
        </div>
      </div>
      <div v-else-if="key=='range'">
        <div v-for="(option, subkey) in each">
          Select {{subkey}}
          <p>
            <label for="min">Min</label>
            <select id="min" v-model="selected[subkey]['min']">
              <option v-for="optiondata in option['options']">{{optiondata}}</option>
            </select>
            <label for="max">Max</label>
            <select id="min" v-model="selected[subkey]['max']">
              <option v-for="optiondata in option['options']">{{optiondata}}</option>
            </select>
          </p>
        </div>
      </div>
    </div>
    <div style="width: 100%; border : 1px solid grey"></div>
    <div>
      Selected Data : <pre>{{selected}}</pre>
    </div>    
  </div>
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f3858696b3c1dd8b">[email protected]</a>/dist/vue.js"></script>

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

I need help getting my Vue.JS project to function properly when it is deployed on a server

After creating a new VueJS project using the Vue UI, I noticed that everything runs smoothly locally at http://localhost:8080/ with no errors. However, when I build the project and upload the files from the dist folder to my hosting package via FTP, I end ...

Perform multiple function invocations on a single variable using JavaScript

Is there a way to execute multiple functions on a single object in JavaScript? Maybe something like this: element .setHtml('test'), .setColor('green'); Instead of: element.setHtml('test'); element.setColor('gre ...

How can I make sure certain properties in the Vuex store don't retain their state after a redirect during server-side rendering (SSR)?

Our approach involves server-side rendering with the use of preserveState to persist all vuex modules' state when navigating between pages. However, we have a specific store where we need to exclude certain properties from persistence. Is there a sol ...

Adjusting the view of an OpenLayers3 map to encompass various vector layers

My OpenLayers3 map includes an OSM Tile layer and one or more Vector layers. I have a function that allows me to zoom into a single layer successfully: vector.addEventListener("change", function() { map.getView().fitExtent(vectorSource.getExtent(), ma ...

Retrieving Distinct Values in CouchDB

In my database, there are documents that represent different rooms. Each room has properties like "floor" and "hotel", among others. What I need to do is fetch all the floors associated with a specific hotel from the database. Something like getAllFloorsOn ...

Steps for exporting all elements of an array to an Excel file using the exceljs library in Node.js

I am facing an issue where I need to export all elements from an array to an Excel file using exceljs in Node.js. Here is an example of my array structure: array image After defining my array, the goal is to create an Excel file that looks like this: exce ...

What methods can be used to replicate a network delay while conducting unit tests for an AngularJS controller?

I am currently utilizing the $httpBackend service within the ngMock module to emulate a GET request. The following is a sample controller code snippet sourced from the AngularJS documentation: // Example controller code function MyController($scope, $http ...

The process of isolating each variable within a JSON data structure

After making an ajax call, my JSON data is currently displayed in this format: {"main_object":{"id":"new","formData":"language=nl_NL&getExerciseTitle=test&question_takeAudio_exerciseWord%5B0%5D=test&Syllablescounter%5B0%5D=test&Syllablesco ...

Transferring information from the service layer to the controller

My goal is to transfer data from a service to a controller using AngularJS. Below is the code I am using: .controller('lista',function($scope,cetrams){ $scope.hola="This is it"; var test; var testfn = function(){ test = &apo ...

When trying to access an array directly within an object, it all too often returns as undefined

There is a React Component that has been provided with an array of objects (main_object), one of which contains another array of objects (secondary_object). Strangely, when trying to print the main object in console.log, the array is visible, but attemptin ...

Ensure that the video continues playing from where the host left off instead of restarting from the beginning upon reloading

Is there a way to seamlessly stream a video from the host server on my website, so that it picks up exactly where it left off rather than starting from the beginning every time someone accesses the site? I want the video to remain synchronized with the o ...

Utilizing the jexcel plugin to seamlessly integrate arrays for a personalized subtitle editing experience

Could you please assist me in understanding how to utilize the jexcel plugin for pushing arrays? To achieve the push functionality, I would like it to behave similarly to arrays containing 6 different colors as outlined below: Subtitles = orange, Caption ...

Utilizing JavaScript in Protractor, explore a list to identify the selected checkboxes and those that remain unchecked

Currently, I am working on developing an end-to-end test using Protractor. My main objective is to extract the names from a list and then determine which checkboxes have been selected and which ones haven't. To check the state of the checkbox, I pla ...

What is the best way to locate the closest element using JavaScript?

Is there a way to locate the closest object to the mouse pointer on a webpage? I have a hypothesis that involves utilizing the array function, however, I am uncertain if that is the correct approach. Furthermore, I lack knowledge of which specific proper ...

Debugging in Javascript involves pausing or breaking at every instance of a javascript function being called

I am currently working on unraveling a complex legacy JavaScript codebase, and I'm finding it challenging to determine where to place breakpoints (having to locate the files and set a breakpoint in Firebug, etc). Is there a way for Firebug to automat ...

Backand - How can I display the contents of variables using console.log() within Security Actions?

Is there a way to utilize console.log() in Backand, specifically within the server side functions like those found under Security & Auth > Security Actions? I have checked the Read.me which suggests using 'console.log(object) and console.error(obje ...

Using Jquery to input selected dropdown values into a text input field

Currently, I am facing some challenges in achieving this task. My goal is to have the selected option from a dropdown list called programs_dropdown added to a text field named programs_input, with the option values separated by commas. For example: php, j ...

Issue: $controller:ctrlreg The controller named 'HeaderCntrl' has not been properly registered

I am encountering an error while working on my AngularJS program. I have defined the controller in a separate file but it keeps saying that the controller is not registered. Can someone please help me understand why this issue is happening? <html n ...

Meteor - ensuring you're not running two separate React versions

After installing React from atmosphere and react-mixin from npm, I noticed that react-mixin depends on react. Does this mean there are two instances of React running in my app? I tried checking my node_modules folder but couldn't find 'react&apos ...

Having trouble accessing my fullstack Vue and Express app due to login application error

Currently, I am immersed in a tutorial that guides me through the creation of a comprehensive register-login application using Vue.js on the front-end, Express on the back-end, and MongoDB. Everything works smoothly when I register a new user and then log ...