Connecting Checkboxes and Chips Together in Vue js (Bi-Directional Binding)

Hey there, I'm new to using Vue Js and I'm facing an issue with selecting a dropdown option from a form. The options are displayed as checkboxes within a div, and when a checkbox is selected, a chip should appear with the label of the checkbox. However, currently, the checkbox is automatically being selected and the chips are appearing without user interaction. Ideally, the chips should only display after selecting a checkbox and deselecting the checkbox should remove the chip. Unfortunately, this is not happening as expected. Below is the code snippet, any help would be appreciated.

   <template>
    <div id="app">
     <v-layout row wrap>
         <v-flex v-for="chip in chips" xs12 sm4 md4>
          <v-checkbox   :label="chip.name" v-model="chip.text"></v-checkbox>
          //  checkbox not working
          </v-flex>
        <div class="text-xs-center">
       <v-select
       :items="dataArr"
        v-model="sensorDM"
       label="Select"
      class="input-group--focused"
     item-value="text"
     @change="call(sensorDM)"
       ></v-select>
       <v-chip
          v-for="tag in chips"
          :key="tag.id"
          v-model="tag.text"
          close
        >
        {{ tag.name }}
        </v-chip> 
        <br>
        </div>
      </div>
    </template>
    <script>
    import axios from 'axios'
    export default {
      name: 'Creation',
      data: () => ({
       chips: [{
          id: 1, text: 'Device 1', name: 'Device 1'
        }, {
          id: 2, text: 'Device2', name: 'Device 2'
        }],
        chip1: false,
        chip2: true,
        dataArr: []
      }),
      created () {
        let self = this
        axios.get('http://localhost:4000/api/devices')
    .then(function (response) {
     self.fData(response.data.result)
    })
      },
      methods: {
      fData: function (message) {
      let self = this  
      message.forEach(function (el, i) {
        self.dataArr.push(el.sDM.name)
      })
    },
        call (mes) {
          let self = this
          axios.get('http://localhost:4000/api/part1/Models/' + mes)
    .then(function (res) {
      self.resObj = res.data.response
      self.resObj.forEach(function (el, i) {
        el['text'] = el.name
        el['isOpen'] = 'false'
      })
      self.chips = self.resObj
    })
        },
        submit(){
             console.log('hjkh')
        }    
      }
    }

I have made some changes to the code and included the call function within the created() method.

Answer №1

If you're looking to achieve a similar result, you can refer to this example: https://codepen.io/ittus/pen/VxGjgN

<div id="app">
   <v-flex v-for="chip in chips" :key="chip.id" xs12 sm4 md4>
      <v-checkbox :label="chip.name" v-model="chip.selected"></v-checkbox>
      <v-chip
         v-model="chip.selected"
         close>
         {{ chip.name }}
      </v-chip>
   </v-flex>
   <div class="text-xs-center">
   </div>
</div>

new Vue({
  el: '#app',
  data() {
    return {
      chips: [{
      id: 1, text: 'Device 1', name: 'Device 1', selected: false
    }, {
      id: 2, text: 'Device2', name: 'Device 2', selected: false
    }],
    chip1: false,
    chip2: true,
    }
  }
})

To make the v-checkbox and v-chip work correctly with boolean values, I included the selected attribute as it's not the default behavior.

Answer №2

I made one final attempt to grasp your use case and demonstrate a simplified solution without vuetify and axios on how to achieve what I believe you are aiming for.

Visit CodePen for the example

Here is the HTML:

<div id="app">
    <div id="v-layout" row wrap>
       <div class="text-xs-center">
          <select
              v-model="selectedDevice"
              @change="getChips(selectedDevice)">

            <option 
                v-for="device of devices"
                :key="device.id">
                {{device.name}}
            </option>
          </select>
        <br>
       </div>

       <div id="v-flex"
            v-for="chip in chips" xs12 sm4 md4>

            <input id="v-checkbox" 
                   type="checkbox"
                   v-model="chip.selected"
            >
            <label for="v-checkbox">{{ chip.name }}</label>
        </div>
  </div>
</div>

And the JavaScript code:

new Vue({
  el: '#app',
  data: () => ({
   devices: [],
   chips: [],
   selectedDevice: {}
  }),
  created () {
    // Simulated call using axios to fetch devices - returning hardcoded device values
    this.devices =  [
     { id: 1, text: 'Device 1 text', name: 'Device 1'},
     { id: 2, text: 'Device2 text', name: 'Device 2'}
    ];
  },
  methods: {
    getChips (device) {

      console.log(device);
      // Simulated call using axios to retrieve specific data based on device selection
      // axios.get('http://localhost:4000/api/part1/Models/' + mes)

      // The following if-else statements are placeholders to mimic axios behavior
      if(device === 'Device 1') {
        this.chips =  [
          { id:1, name:"Chip_WH", selected: true}, 
          { id:2, name:"Chip_EH", selected: false}
        ];
      }
      else {
        this.chips = [
          { id:1, name:"Chip_BL", selected: false}, 
          { id:2, name:"Chip_CK", selected: true}
        ];
      }
    }
  } 
});

Answer №3

I've simplified your codepen to demonstrate how to achieve this:

Check out the simplified version here

HTML:

<div id="app">
   <div v-for="chip of chips" :key="chip.id" xs12 sm4 md4>
     <input type="checkbox" v-model="chip.selected">
     <label for="checkbox">{{ chip.name }}</label>
  </div>
</div>

JS:

new Vue({
  el: '#app',
  data: () => ({
   chips: [
     { id: 1, text: 'Device 1', name: 'Device 1', selected: false},
     { id: 2, text: 'Device2', name: 'Device 2', selected: true}
   ]
  })
});

The checkboxes will always be selected because the v-model is bound to chip.text. I added a selected property to the chips so you can bind to chip.selected instead.

I hope this explanation helps!

In addition, I recommend checking out the well-documented and helpful guides from vue.js:Vue.js Guides

Warm regards, Georg

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

A guide on how to pass an object as a parameter when opening a new view in JavaScript using the MVC pattern

Within my application, I have two pages - page A and page B, each with its own model. Both pages are loaded by the HomeController as shown below. public class ModelA { public string UserName { get; set; } public int UserID { get; set; } } public ...

Developing object in place of an array (JavaScript)

After receiving data from the back-end, I handle it within a function: getAgentSuggestionById(agentId) { this._agentsService.getAgentSuggestionById(agentId).subscribe(result =>{ this.agent = result.items.map(e => {let obj = {name: e.name ...

There seems to be a malfunction with the sorting of numbers in Datatables

My experience with datatables on my page has been mostly positive, except for one issue with sorting on the number field. The sorting seems to be off, and I've included an illustration to demonstrate the problem. Additionally, I've tried to addr ...

Enhance user experience with a dynamic Bootstrap combo box that updates based on

I am currently facing an issue with the bootstrap combobox plugin. I am having trouble changing the selection and sending that information from the view to the controller. $('#MyCombo').on('change', function () { var data = $(this) ...

Error in overwritePermissions caused by a bug

message.guild.channels.create(`ticket-${message.author.username}`).then (channel => channel.overwritePermissions(Support, { SEND_MESSAGES: true, READ_MESSAGES: true ...

Dynamically render components/templates based on the route parameter in Vue.js

I am wondering if it is possible to implement this feature using Vue.js, where the code would load a page or template based on a parameterized URL. I have spent some time searching for a solution with no success, perhaps I am using the wrong keywords. My ...

The menu header is experiencing issues with alignment

I've been tackling the alignment of elements in my menu header, but for some reason, they're not lining up horizontally as intended. Instead, they are stacked below each other. Here's the link to my jsfiddle Here's a snippet of my HTML ...

What is preventing me from accessing the user's data through the context API?

I am currently grappling with understanding the context API. In my CardTemplate file, when I console.log(users), all the saved data shows up. However, I am struggling to consume this data in UserProfile.jsx. I need the data in UserProfile.jsx, but I am enc ...

In Photoshop scripting, trying to manipulate an undefined object is like trying to find

I am facing an issue in Photoshop while trying to create a grommet using a script. The error message I receive is: Error: undefined is not an object line 63 ( grommetMarkL = printMarksLayer.pathItems.ellipse( -(spacingY), spacingX, grommetSize, gromm ...

"XMLHttpRequest 206 Partial Content: Understanding the Importance of Partial

I need help with making a partial content request using an XMLHttpRequest object in JavaScript. Currently, I am trying to load a large binary file from the server and want to stream it similar to how HTML5 video is handled. While setting the Range header ...

Interactive calendar feature with a popup that appears when hovering over an event

I am looking to create a popup on hover with full calendar functionality, similar to the one seen at this link. I have attempted using full calendar with qtip, but I was unable to achieve a clickable popup as it disappears when the mouse moves away. Here ...

Tips for Avoiding "TypeError: fetch failed" on Next.js Page Server Component While Retrieving Data from Spring Boot API

Working on a Next.js application has been quite challenging as I fetch data from my Spring Boot API within a Page server component. Unfortunately, my GitHub Action CI/CD pipeline has been encountering failures during the Docker image build process, specifi ...

Storing the Google Maps API key as a global variable in a Django project

Is there a way to improve the way I open my gmap on multiple pages? {% block extra_js %} <script src="{%static 'js/map.js' %}" type="text/javascript"></script> <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_ ...

Error encountered: The Jquery-ui functionality ceases to operate upon the completion of content

I'm utilizing the jQuery UI library to rearrange the items on my list. Initially, everything works smoothly without any issues. However, when I navigate to another page and then return to the page with my list, I encounter difficulties. It's wor ...

Retrieve the attributes associated with a feature layer to display in a Pop-up Template using ArcGIS Javascript

Is there a way to retrieve all attributes (fields) from a feature layer for a PopupTemplate without explicitly listing them in the fieldInfos object when coding in Angular? .ts const template = { title: "{NAME} in {COUNTY}", cont ...

Updating another component when an input value changes in React

I am currently learning React and I am facing a challenge in updating a component based on an input value. Previously, I had successfully done this using HTML and vanilla JavaScript. Now, I am trying to achieve the same functionality in React but encounter ...

When attempting to call iFrame in JavaScript, it may not be recognized and result

At the moment, I am in the process of developing my personal portfolio and have come across a perplexing issue that has left me stumped. The structure of my webpage operates on a main-frame structure, which means that instead of navigating through separate ...

Avoiding repetition in json array using reactjs with the help of axios

After receiving guidance from @Akrion, I managed to resolve the issue! Check out my comments below our conversation for the solution. I am relatively new to reactJS and axios, but I recently collaborated with a classmate on a project. Now, I find myself s ...

The parent's height dynamically adjusts based on the height of its visible children using only CSS

I am dealing with the following structure: <div class="body"> <div class="wrapper"> <div class="dialog"> <div class="content-0"></div> <div class="content-1&quo ...

Integrate the complete Mozilla pdf.js viewer into a Vue.js application using webpack through vue-cli

I am trying to integrate the full Mozilla pdf.js viewer into a Vue SPA. After reading a Stack Overflow post with an accepted solution, I still can't seem to get it to work. I keep encountering the 'Uncaught SyntaxError: Unexpected token <&apo ...