"Exploring the functionality of Vue JS2 checkboxes within a parent and

I am working with a complex nested list structure:

<ul>
      <li v-for="subregion in continents">
        <input type="checkbox" :id="subregion[0].subregion" > <label :for="subregion[0].subregion">{{ subregion[0].subregion }}</label>
        <ul>
          <li v-for="country of subregion">
              <input type="checkbox" :id="country.name" > <label :for="country.name">{{ country.name }} (+{{ country.callingCodes[0]}})</label>
          </li>
        </ul>
      </li>
</ul>
Entire code available on: https://jsfiddle.net/kw1vmvqy/

I'm looking for a way to create a function that will automatically synchronize the checkboxes of countries with their corresponding continent checkboxes. The goal is to ensure that when a continent checkbox is selected or deselected, all associated country checkboxes follow suit, and vice versa. How can I achieve this seamless synchronization between the two levels of checkboxes?

Answer №1

To start off, make sure to connect values and v-models to your checkboxes:

<input type="checkbox" :id="subregion[0].subregion" v-model="subregionCheck" :value="subregion[0].subregion">

<input type="checkbox" :id="country.name" v-model="countryCheck" :value="country.name">

Additionally, include arrays for subregionCheck and countryCheck in your data:

  data: {
    subregions: null,
    countries: null,
    query: '',
    countryList: [],
    subregionCheck:[],
    countryCheck: []
  },

These arrays act as indicators for our checkboxes: if they contain the value of a single checkbox, it will be checked. Initially, both arrays are empty.

Next, we need to set up a listener for the subregion checkbox along with a function to check all country checkboxes related to that subregion. Start by adding a click listener to the subregion checkbox:

<input type="checkbox" :id="subregion[0].subregion" v-model="subregionCheck" :value="subregion[0].subregion" @click="checkAllCountries(subregion)">

Then define the method (since ES6 is not used, "this" needs to be assigned to a variable):

checkAllCountries: function (subregion) {
        var that = this;
        if (this.subregionCheck.indexOf(subregion[0].subregion) > -1) {
            subregion.forEach(function (element) {
              if (that.countryCheck.indexOf(element.name) <= -1) {
                that.countryCheck.push(element.name);
              }
            });
      }
      else {
         subregion.forEach(function (element) {
            that.countryCheck.splice(that.countryCheck.indexOf(element.name), 1);
        })
      }
    },

Now we must create a method to uncheck the subregion checkbox if any of its corresponding countries are unchecked. Add a click listener to the country checkboxes:

<input type="checkbox" :id="country.name" v-model="countryCheck" :value="country.name" @click="checkSubregion(subregion)"> 

Then define the method:

checkSubregion: function (country) {
  if ((this.countryCheck.indexOf(country.name) <= -1) && this.subregionCheck.indexOf(country.subregion) > -1 ) {
    this.subregionCheck.splice(this.subregionCheck.indexOf(country.subregion), 1);
  }
},

View demo

Answer №2

Your inquiry poses a significant challenge that cannot be fully addressed here. For more insights, you can refer to this resource. This resource demonstrates how countries under a subregion are checked when the subregion is selected, but the reverse is not implemented completely. By following this approach, you can create dynamic model binding, albeit with a potential drawback of reduced speed due to the requirement of traversing multiple components upon each change.

<ul>
  <li v-for="(subregion, index) in continents">
    <input type="checkbox" :id="subregion[0].subregion" v-on:change="onSubregionChecked(subregion[0].subregion)">
    <label :for="subregion[0].subregion">{{ subregion[0].subregion }}</label>
    <ul>
      <li v-for="country in subregion">
        <input type="checkbox" v-on:change="onCountryChanged(country)" v-model="countryMap[country.alpha3Code].isChecked" :id="country.name">
        <label :for="country.name">{{ country.name }} (+{{ country.callingCodes[0]}})</label>
      </li>
    </ul>
  </li>
</ul>

For implementation in the script:

fetchData: function() {
  var xhr = new XMLHttpRequest();
  var self = this;
  xhr.open('GET', apiURL);
  xhr.onload = function() {
    self.countryList = JSON.parse(xhr.responseText);
    _.each(self.countryList, function(country) {
      self.countryMap[country.alpha3Code] = {
        country: country.alpha3Code,
        isChecked: false,
        subRegion: country.subregion
      };
    });
  };
  xhr.send();
},
onSubregionChecked(val) {
  const self = this;
  self.countryMap = _.mapValues(self.countryMap, function(countryInSubRegion) {
    if (_.isObject(countryInSubRegion) && countryInSubRegion.subRegion === val) {
      countryInSubRegion.isChecked = true;
    }
    return countryInSubRegion;
  });
}

Please note that this is just a conceptual guideline and not a fully functional solution. It aims to provide a starting point for your development journey.

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

Update object properties in Angular controller dynamically

Take a look at my simple plunker Within the code, I am attempting to link a scope variable to an object property. $scope.name = 'World'; var obj = { "name":$scope.name } $scope.$watch('name', function(){ console.log(obj["name"]); ...

Isotope data-filter not working properly following an Ajax callback

I'm looking for a way to create a filter that can be dynamically updated: I have utilized the isotope javascript library in an external script file: var $container = $('.isotope'); // initialize isotope $container.isotope({ ...

Tips for Customizing Dialogs with CSS Classes in mui5 Using Emotion/Styled

When attempting to customize the styling of a mui Dialog, I encountered an issue where it wouldn't accept className even when placed inside PaperProps. While inline styles worked, my preference was to import styles from a separate stylesheet named Sty ...

PHP isn't getting the AJAX POST data from the JavaScript file

I've been stuck on this issue for hours now, unable to find a solution. Here is the javascript code snippet: function sendMovement(cel) { var name = "test"; $.ajax({ type: 'POST', url: '../game.php', ...

Top method for identifying browser window modifications such as navigating back, altering the URL, refreshing, or closing the window

Currently, I am developing a testing application that requires me to trigger a finsihTheTest() function in specific situations. These situations include: When the user attempts to reload the page. When the user tries to navigate back from the page. If the ...

What is the best way to continuously run a series of functions in a loop to create a vertical news ticker effect?

I'm in the process of creating a vertical latest news ticker, and although I'm new to javascript, I'm eager to learn and build it myself. So far, I've come up with this, but I want the news cycle to restart once it reaches the end. ...

Share the hyperlink to a webpage with someone else

In my SQL command, I have a unique feature that retrieves the complete URL value of the current page: [##cms.request.rawurl##]. This code returns the entire URL. I need to send this address to another page and load it into a special div called "load-fac". ...

Achieving a delayed refetch in React-Query following a POST请求

Two requests, POST and GET, need to work together. The POST request creates data, and once that data is created, the GET request fetches it to display somewhere. The component imports these hooks: const { mutate: postTrigger } = usePostTrigger(); cons ...

What is the proper method for effectively employing destructuring?

I'm trying to figure out how to properly return state with a fetched array using the spread operator. Here is my reducer code snippet: function themes(state = [], actions){ switch(actions.type){ case FETCH_THEMES_SUCCESSFULLY: const { th ...

Is there a way to separate a string using two different delimiters?

Here is my code snippet : <template> ... <p v-for="club in clubs">{{club}}</p> ... </template> <script> export default { data: () => ({ clubs: '' }), mounted () { let dataClub = "- ...

Conceal Navigation with jQuery

Seeking assistance with jQuery for a new project. I'm trying to create a navigation menu that will automatically disappear after 3 seconds when a user enters the page. In its place, an arrow will be displayed instead of the original menu. Once the a ...

Generate a visually dynamic representation of a live website page

I'm curious if it's possible to create a login page similar to the one shown in this image, using HTML, CSS, and Javascript. Instead of a traditional background image, I want the background to display the actual layout of another website, such a ...

Can JQuery's 'unslider' be customized to only change the backgrounds?

Check out my source at this link: http://codepen.io/anon/pen/Bvkjx Observe how the content and background images rotate correctly. Now, I'm curious if it's feasible to keep the following content static <p>SOME CONTENT1</p> while ...

execute function once eventlistener completes running

I've implemented a code snippet to detect the availability of a gyroscope for user interaction. Here's how it works: function check_user_hardware(){ window.addEventListener("devicemotion", function(event){ if(event.rotationRate.alpha ...

What is the best method to retrieve the audio attributes of the currently playing song using the Spotify Web API?

Check out this link for more information on using the Spotify web API to access audio features of tracks. Hello, I am currently utilizing the Spotify web API to retrieve audio features of a track. However, the API documentation only explains how to obtain ...

Challenges in developing complex single-page applications

Currently, I am in the process of developing an extensive single-page web/javascript application that is going to be quite large. The technologies I am utilizing include ASP.NET MVC4, jquery, knockout.js, and amplify.js. One obstacle I am encountering is ...

Tips for sequentially arranging and rearranging an array of numbers, even when duplicates are present

Encountered a perplexing issue that has me scratching my head in an attempt to visualize a solution. Currently, I am working with an array of objects that appears as follows: let approvers = [{order:1, dueDate: someDate},{order:2, dueDate: someDate}, ...

Assign a specific value to each object

Receiving data from the backend in a straightforward manner: this.archiveService.getRooms(team).subscribe( res => { this.form = res; this.form.forEach(el => { el.reservation.slice(-6).match(/.{1,2}/g).join('/'); }); }, ...

The promise in app.js at line 51471 was caught with an error stating that the navigation from "/customer/login" to "/customer/dashboard" was cancelled due to a new navigation instance

After logging in, I am trying to redirect to another page using router push, but encountering an error. app.js:51471 Uncaught (in promise) Error: Navigation cancelled from "/customer/login" to "/customer/dashboard" with a new navigation ...

Utilizing Razor Syntax within VueJs Component

To prevent redundant code, I am utilizing VueJs component functionality to create a component that contains the Select dropdown list. Here is the code snippet: Vue.component('select-component', { template: ` <label>elT ...