Display a checkbox and automatically mark it as checked if a value from one dataset is found in another dataset

I am trying to check whether a value exists from one dataset to another dataset. Specifically, I want to utilize the id property for this purpose.

I have been experimenting with handlebars.js, but the code below is not functioning properly.

Here is the spot_categories array:

{spot_categories:[{category:1},{category:2},{category:3},{category:4},{category:5},{category:6}]}

And here is the data array:

{data:[{spot_category_id:1},{spot_category_id:3}]}

Below is the vue.js code I have so far:

<!-- check if a variable exists -->
{{# var ok = false}}
<!-- iterate through categories -->
<li v-for="(category,j) in spot_categories">
  <label>
        <!-- iterate through data array -->
        <template v-for="(val, l) in data">
           <!-- check if spot_category_id matches category.id -->
           <template v-if="val.spot_category_id == category.id">
              {{ ok = true }}
           </template>
        </template>
        <!-- if ok is true, display the value -->
        <input :value="category.id" :checked="ok">
  </label>
</li>

Can someone please assist me with this issue? Thank you!

Answer №1

In this scenario, the template loops through the spot_categories dataset only once and then calls a method to check if its id exists in another dataset. The decision on which checkbox element to render is made using v-if and v-else. The evaluation method utilizes array.some() which is the most suitable approach here (although a manual for loop can also be used but may result in longer and less elegant code).

new Vue({
    el: categoryContainers,
    data: {
      spot_categories: [
        {id: 1},
        {id: 2}
      ],
      data: [
        {spot_category_id: 1},
        {spot_category_id: 3}
      ]
    },
    methods: {
      checkIfExists: function(item1){
         return this.data.some(function(val){ return val.spot_category_id == item1.id });
      }
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>

<div id="categoryContainers">
   <ul>
      <li v-for="(category,j) in spot_categories">
         <label>
            <input type="checkbox" v-if="checkIfExists(category)" :value="category.id" checked>
            <input type="checkbox" v-else :value="category.id">
            {{ 'Category ID ' + category.id }}
       </label>
      </li>
    </ul>
</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

Methods for displaying data on the client side using express, MongoDB, and jade

I'm currently working on displaying data retrieved from my database using node.js, Express, and MongoDB. I successfully see the data in the console, but now I need to output it on the front-end using Jade. Here is the data I have retrieved: { date: ...

Converting JavaScript objects into a JSON string and then into a PHP array via POST

Hello everyone, I could really use some assistance with this issue. I am passing a JSON object to PHP like so: var x = {}; x.xt = {}; x.xt.id = id; x.xt.to = foo; somearray.push(x); To convert the object to JSON: $.toJSON(x); The resulting JSON string ...

What is the best way to notify the user if the percentage entered is not a numeric value?

My role is to notify the user when the entered value exceeds the acceptable range: if (document.myForm.outputPercentage.value <= 0 || document.myForm.outputPercentage.value >= 100) { alert( "Please enter a percentage between 1 and 100 ...

Displaying a dynamic menu using Angular's ngFor loop

I am attempting to create a menu with sub-menus. The desired structure for my menu is outlined below. However, the demo I'm testing is not producing the correct structure. Check out the demo here. "Sub Test": { // Main menu "Example1":"hai",//sub ...

Unlock the secrets of recovering deleted data from a text area in Kendo UI Angular

Currently working with Kendo UI for Angular, I need to capture deleted content and remove it from another text area within the same component. My project is using Angular-13. I'm stuck on how to accomplish this task. Any suggestions would be greatly ...

How can I pan/move the camera in Three.js using mouse movement without the need to click?

I am currently working on panning the camera around my scene using the mouse. I have successfully implemented this feature using TrackballControls by click and dragging. function init(){ camera = new THREE.PerspectiveCamera(45,window.innerWidth / windo ...

Updating an object with AngularJS

Let's consider the code snippet below: var absenceType = {name: 'hello'}; this.newAbsenceType = angular.copy(absenceType); After making changes to this.newAbsenceType, you want to apply these changes to the original object. I have explore ...

Troubleshooting Problems with Ruby Arrays, JavaScript, and JSON

I am facing a challenge with rendering a highcharts plugin in my rails application. I suspect it could be related to the sql queries fetching data from the database and converting them into a ruby array that the javascript code fails to interpret correctly ...

Issue with jQuery fadeTo() not working after appendTo() function completes

I am facing a problem with the code below that is meant to create a carousel effect for my website. The main issue I am encountering is that the original fadeTo() function does not actually fade the elements, but rather waits for the fade time to finish an ...

Enhance your user interface with an interactive Bootstrap dropdown using Angular

I have a program where users can choose from 3 options such as: Hi, Hello and Hey. Currently, when a user selects one of the values, they receive a message saying that they need to "select a value." I am struggling to figure out how to update the ng-model ...

Do you need to have knowledge in reactjs in order to master react-native?

As I embark on the journey of learning how to build apps using react-native, a burning question arises in my mind: should I first learn react-js before diving into react native? Any guidance or advice would be greatly appreciated. Thank you. ...

I'm struggling to grasp how to effectively utilize a JSON Object in this situation

In my coding project, I am looking to utilize Javascript in order to create a JSON or array that will house pairs of data for 'id' and 'ip'. This way, if I need to retrieve the 'ip' for a specific 'id=123', I can eas ...

Change the controller's classes and update the view in Angular

In my angular application, I have a popup window containing several tabs. These tabs are styled like Bootstrap and need to be switched using Angular. The code for the tabs is as follows (simplified): <div class="settingsPopupWindow"> <div> ...

Vue.js CSS class interpolation

Is there a way to apply CSS classes dynamically in Vue.js? {{ category.icon }} --> "icon1" I am trying to achieve the following: <i :class="category.icon" class="icon icon-"></i> The desired output should be: ...

The invocation of $.ajax does not work as a function

I'm encountering an issue when running npm start and trying to access the browser, I keep getting this error message in the stack trace. Error: $.ajax is not functioning properly at findLocation (G:\CodeBase\ExpressApp\routes\ind ...

Transforming a Formdata object into a JavaScript array

Greetings everyone! Is there a way in JavaScript to convert this data structure: { Control[0].Eseguito: "true" Control[0].Id:"2" Control[0].Nota:"" Control[1].Eseguito: "true" Control[1].Id:"2" Contr ...

Personalized path-finding tree iterator

I am trying to implement a custom iterator in JavaScript that can traverse a DOM tree based on specific criteria provided by a callback function. The goal is to return an array of the nodes that match the criteria as the generator iterates through the tree ...

Exploring and extracting values from nested arrays of objects in JavaScript and React

Hey there, I am having trouble getting the data from the backend server to display on a chart library. Can you please take a look at my code and help me out? const data = [ { id: "americano", data: [{x: "10",y: 10,}, {x: &quo ...

Leveraging JavaScript to identify web browsers

I am looking to implement a feature on my website where if the visitor is using Internet Explorer 8.0 or an earlier version, they will receive an alert prompting them to upgrade their browser before proceeding. For users with other browsers, the page will ...

Building chat rooms using VueJS

For my project, I am developing a Queue System using Node (SocketIO), VueJS, and MySQL. The goal is to automatically create a new chat room once 5 people have joined the queue. I already have the main chat component created, but now I need to figure out ...