VueJS restricts the selection of only one checkbox based on its class name

I am working with a group of checkboxes:

<div class="options">
  <input type="checkbox" value="10" v-model="choices">
  <input type="checkbox" value="30" v-model="choices">
  <div class="group">
    <input type="checkbox" value="50" v-model="choices">
    <input type="checkbox" value="70" v-model="choices">
  </div>
</div>

I am storing the checked values in a data variable:

new Vue({
  el: '#app',
  data() {
    return {
      choices: [],
    }
  },
});

I am struggling to find a way to limit checking more than one checkbox inside the .group element. I initially considered using radio buttons, but encountered some issues, so I decided to continue with checkboxes. I believe I could achieve this using jQuery or vanilla JS, however, I am unsure about where to implement the check (on change event method?). What would be the best approach to accomplish this in VueJS?

You can view my code on CodePen here: https://codepen.io/RomkaLTU/pen/LXOJgr?editors=1010

Answer №1

There are various ways to achieve this:

1. :disabled directive

<input type="checkbox" value="20" v-model="additional" :disabled="condition">

You can disable the checkbox by setting a condition such as additional.length > 0 to prevent multiple selections.

2. Watchers

data() {
  ...
},
watch: {
  additional(newValue, oldValue) {
    // Triggered whenever a checkbox is switched
  }
}

Answer №2

It's important to shift your mindset away from focusing on the DOM and classes, even though it can be a difficult habit to break.

<input type="checkbox" value="50" v-model="additional" :disabled="hasAdditional">

computed: {
  hasAdditional() {
    return this.additional.length > 0
  }
}

Start by using this code snippet as a foundation for what you are trying to accomplish. You may need to implement a watcher to detect changes and uncheck items that are not allowed. Alternatively, consider modifying hasAdditional to calculate the total number of additions, which can then determine if the group can be selected.

Avoid relying solely on CSS classes. Instead, utilize methods, watchers, and computed properties to handle the logical operations effectively.

Answer №3

Thank you for bringing this to my attention, however I opted for a solution that does not involve disabling input as it can be very confusing for the end user. Here is what I implemented:

<input type="checkbox" value="30" v-model="additional">
<input type="checkbox" value="40" v-model="additional">
<input type="checkbox" value="10" v-model="additional_grouped" @change="uniqueCheck">
<input type="checkbox" value="20" v-model="additional_grouped" @change="uniqueCheck">


new Vue({
  el: '#app',
  data() {
    return {
      additional: [],
      additional_grouped: [],
    }
  },
  computed: {
    final: function(){
      return this.additional.concat(this.additional_grouped);
    }
  },
  methods: {
    uniqueCheck(e){
      this.additional_grouped = [];
      if (e.target.checked) {
          this.additional_grouped.push(e.target.value);
      }
    }
  }
});

Answer №4

To ensure the list of checkboxes is cleared each time an option is selected, simply implement a function for this purpose:

<div class="additions">
<input type="checkbox" value="10" v-model="additional" v-on:click= "check_one()">
<input type="checkbox" value="30" v-model="additional" v-on:click= "check_one()">
</div>
<script>
data(){
return {
additional: [], 
}
},
methods: {
check_one: function(){
this.additional = [];
}       
}
}
</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

Leveraging parameters within a sequence of object properties

Within the realm of Angular, I am dealing with interfaces that take on a structure similar to this (please note that this code is not my own): export interface Vehicles { id: number; cars: Car; trucks: Truck; } Export interface Car { make: ...

Developing a Multi-Faceted Array Utilizing SQL Data

The requirement of the plugin I am using is to provide it with an array structure in JavaScript that looks like this: var data = [ { "id": 1, "name": "University1", "list": [ {"id": 1, "name": "Dorms", "list": ...

Locate the upper and lower limits within an array

I'm currently working on extracting the upper and lower boundaries for a numeric value within an array. const boundaries = [15, 30, 45, 60, 75, 90]; const age = 22; In the given example, the expected result would be: [15, 30] If the value matches ...

Direct attention to the modal display

I'm having trouble auto-focusing an input field when a modal is displayed. Here's what I've tried, but it doesn't seem to be working: jQuery(document).ready(function($) { $('#myModal').on('show.bs.modal', functi ...

Setting the current date of a jQuery datepicker to the value of an input tag

I am looking to assign a value to an input tag that has a datepicker attached to it. Upon initialization of the datepicker, I want to set this value. Below is a hypothetical example of what I am trying to achieve: HTML: <input id="test" value="">&l ...

Retrieve image details and display them in the console when the page is resized

Query: How can I retrieve and monitor the src, width, and height of all images on a webpage and display this information in the console whenever the page's size changes? Sample Code Snippet: var images = document.getElementsByTagName('img' ...

Combining Data from Header to Body using HTML5 and JavaScript

I am struggling to figure out how to transfer variables declared in the script from the header of my code to the body. Specifically, I want to capture the user input in the script and replace a placeholder in the body. Here is an example of what I am tryin ...

Creating a seamless rotation effect on an SVG shape at its center across all browsers, even Internet Explorer

Is there a way to make an SVG figure rotate around its center? I have been trying to calculate the rotation center and scale it based on the viewBox. It seems to work perfectly fine in Chrome, Firefox, and Safari, but I just can't seem to get it to wo ...

The Semantic UI dropdown consistently fails to return a value

I am currently utilizing Semantic UI for an ASP.NET core project, and I am encountering an issue when trying to submit a form that contains a drop-down element. Despite my efforts, it always returns null, and the lack of proper documentation on this matter ...

What is the quickest way to increase value in the DOM?

Is there a more efficient method for incrementing a DOM value that you know of? let progress = +document.getElementById("progress").innerHTML; progress++; document.getElementById("progress").innerHTML = progress; Perhaps something like t ...

The Axios post request is mistakenly sending my data as the key with an empty value instead of sending the entire data object itself

I began by developing the frontend, but now I am looking to create the backend in order to establish a connection with a database. const express = require("express"); const bodyParser = require("body-parser"); const cors = require(" ...

Receiving a XHR 404 error when trying to upload an mp3 file, even though the directory clearly

I am currently working on a project where users will be able to upload an mp3 file of their choice through JavaScript and AJAX. Here's the code snippet I have so far: // Creating the file upload button var uploadBtn = document.createElement("input"); ...

What is the best way to make tooltips track a specific data point they are connected to in D3?

I am working with a figure created using D3 that includes tooltips appearing near a data point when hovered over and can be pinned by clicking on the point. I have implemented the functionality to change the plotted values for the points by clicking on spe ...

Transform your HTML audio player into a Vue component

I am in the process of converting an HTML player into a Vue component. Half of the component has been successfully converted, but the time control slider is still missing. Below is the original HTML code for the player: // JavaScript code for the audi ...

Attempting to find a solution to successfully transfer an object from the jEditable datatable plugin to my Java Servlet

Currently, I have a Datatable set up and I am utilizing the jeditable plugin to make cells editable and update data. However, after editing a cell and hitting enter, when the data is sent back to my URL Rest endpoint (where I simply have a System.out.print ...

Encountering invalid JSON response while making an API request

Struggling to integrate GoToMeeting's API by sending a POST request to create a meeting. Currently, attempting to manually code the meeting body and send the necessary headers, but encountering an issue with invalid JSON error. Below is the code snipp ...

Forcing the rendering of a Vue.js component

I am completely new to vue and struggling to figure out how to render a component programmatically. My current project involves using the Leaflet JavaScript library where I have created a wrapper component for rendering maps and adding markers. The issue a ...

Accessing files from various directories within my project

I'm working on a project with 2 sources and I need to import a file from MyProject into nest-project-payment. Can you please guide me on how to do this? Here is the current file structure of my project: https://i.stack.imgur.com/KGKnp.png I attempt ...

The data array generated from an axios request is not being rendered properly on the chart using Chart.js

I am facing an issue with my API endpoint that returns an array of 24 values which I want to utilize in a chartjs within a vue component. Despite no errors on page load, the bars on the charts are not displaying and the reason remains unknown to me. UPDA ...

Turning text into clickable links using JavaScript

I am faced with a scenario where I need to detect phone numbers within a string and convert them into clickable links. At the moment, using an external library is not an option. Here's the progress I've made so far: String: "This is my phone nu ...