Vue JS: Toggling Checkbox Selections

I'm attempting to create a functionality where checking one checkbox will uncheck another, similar to how radio buttons work. I'm relatively new to Vue.js, so I may be missing something in my code. Here are the two input elements:

<label for="'product-'+product.id"
     class="none addon_label"
     :class="{'addon_selected': !selected}"
     >

<input class=""
       type="checkbox" 
       :id="'product-'+product.id"
       :value="false"
       v-model="selected"/>

<div class="v-center">None</div>
</label>

<label :for="'product-'+product.id"
     class="is_flex addon_label"
     :class="{'addon_selected': selected}"
     :data-product-id="product.id">
<div class="checkbox-container">
<input class=""
       type="checkbox"
       :value="true"
       :id="'product-'+product.id"
       v-model="selected"/>
</div>

Recording demonstrating the issue

Answer №1

Consider using radio buttons in place of checkboxes:

new Vue({
  el: "#demo",
  data() {
    return {
      product: {id: 1},
      selected: false
    }
  }
})
.addon_selected {
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <label for="'product-'+product.id"
       class="none addon_label"
       :class="{'addon_selected': !selected}"
       >
  <input class=""
         type="radio" 
         :id="'product-'+product.id"
         :value="false"
         v-model="selected"/>
  </label>
  <label :for="'product-'+product.id"
       class="is_flex addon_label"
       :class="{'addon_selected': selected}"
       :data-product-id="product.id">
  <input class=""
         type="radio"
         :value="true"
         :id="'product-'+product.id"
         v-model="selected"/>
         
  </label>
</div>

Answer №2

In my opinion, utilizing two variables would be an effective approach to achieve the desired behavior similar to checkboxes but with radio button characteristics.

There are two functions called setInitial and setEnd, where each function clears the other input. Surprisingly, the checkbox behavior remains unchanged, allowing users to clear or reset inputs by double-clicking on the same input.

new Vue({
el: "#app",
data: {
  initial: false,
  end: false
},

methods: {
  setInitial: function(){
    this.end = false
  },
  setEnd: function(){
    this.initial = false
  }
}

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <label
    class="none addon_label"
    :class="{'addon_selected': !initial}"
  >Initial</label>
  <input 
    type="checkbox" 
    v-model="initial"
    @click="setInitial"
  />
  ==#==

  <label
    class="is_flex addon_label"
    :class="{'addon_selected': end}"
  >End</label>
  <input
     type="checkbox"
     v-model="end"
     @click="setEnd"
  />
<hr>
Initial {{ initial }} - End {{ end }}
<hr>
  
</div>

I encourage you to run the snippet provided and test out this solution for yourself.

Answer №3

If you find yourself in a situation where checkboxes are necessary instead of radio buttons, one trick is to switch the true-value and false-value props of one checkbox. This will make it behave like a radio button.

new Vue({
el: "#app",
data: {
  selected: false
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
<label for="first_input"
     >False</label>
<input
       type="checkbox" 
       id="first_input"
       v-model="selected"
       :true-value="false"
       :false-value="null"/>

<label for="second_input"
     >True</label>
<input
       type="checkbox" 
       id="second_input"
       v-model="selected"
       :false-value="null"/>
       
<br/>
       
Input value: {{ selected }}

</div>

Answer №4

Feel free to give this a shot.

<label for="'product-'+product.id"
     class="none addon_label"
     :class="{'addon_selected': !selected}"
     >

<input class=""
       type="radio" 
       :id="'product-'+product.id"
       :value="checkStatus"
       @change="check($event.target.value)"/>

<div class="v-center">None</div>
</label>

<label :for="'product-'+product.id"
     class="is_flex addon_label"
     :class="{'addon_selected': selected}"
     :data-product-id="product.id">
<div class="checkbox-container">
<input class=""
       type="radio"
       :value="checkStatus"
       :id="'product-'+product.id"
       @change="check($event.target.value)/>
</div>

In the component script, you are able to create the check() method within the methods section.

<script>
export default {
    data() {
        return {
            checkStatus: false
        }
    },
    methods: {
        check: function(val) {
              this.checkStatus = !val;
        }
    },
}
</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

Creating a canvas with multiple label introductions can be achieved by following these

I am looking to group labels and sublabels on the x-axis of a canvas component. Currently, I only have sublabels like: RTI_0, RTI_1... I would like to add labels to these sublabels like: RTI = {RTI_0,RTI_1,RTI_2] BB = {BB_0, BB_1,BB_2,BB_3] <div cla ...

What is the best way to transfer information between two separate Javascript controller files?

My current situation is a bit complex, but I believe there must be a straightforward solution. I have two Javascript controller files: one named rootPageClient.js and another called findPollClient.js. Additionally, there's a file called ajax-function ...

Using Node and Express to handle form submissions, we can create a POST request that sends data to the server

Despite my ongoing learning journey, I am feeling a bit frustrated as I struggle to find a solution for this particular issue using ES6 Javascript. Currently, I have a straightforward todo-list web-app where everything is managed and displayed through the ...

Using 'interface' declarations from TypeScript is unsupported in JS for React Native testing purposes

I have a ReactNative app and I'm attempting to create a test using Jest. The test requires classes from a native component (react-native-nfc-manager), and one of the needed classes is defined as follows export interface TagEvent { ndefMessage: N ...

"Looking to trigger a server click using JQuery or Javascript in your code? Here's how you can

I am facing an issue with triggering a Server-Side OnClick event on an ASP Server Button within a User Control using JavaScript or JQuery. The current methods I have tried do not produce the desired result as they do not actually simulate a user clicking t ...

Display only the relevant search results using ng-show in AngularJS

By utilizing the code below, I am able to filter results where all entries are displayed on the page: <body ng-app=""> <div ng-init="friends = [{name:'John', phone:'555-1276'}, {name: ...

Error encountered: Uncaught SyntaxError - An unexpected token '<' was found while matching all routes within the Next.js middleware

I am implementing a code in the middleware.ts file to redirect users to specific pages based on their role. Here is the code snippet: import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' import { get ...

What is the best way to execute 2 statements concurrently in Angular 7?

My goal is to add a key rating inside the listing object. However, I am facing an issue where the rating key is not displaying on the console. I suspect that it might be due to the asynchronous nature of the call. Can someone help me identify what mistak ...

Is there a way to retrieve files stored on my hard drive within a webpage?

I have a large number of files stored on my hard drive, all following the same format, 2014.C1.012.012 - full name of the file. They each have unique numbers and names. I want to create a local webpage where I can organize these files into a table w ...

What is the best way to link a mutable object with an immutable reactive object?

A unique composable function called useApplicationPreferences() is utilized in Vue 2 with the Composition API. This specific function provides access to a non-writable computed ref named darkMode: //useApplicationPreferences.ts import { reactive, computed ...

Generating input fields dynamically in a list and extracting text from them: A step-by-step guide

I am designing a form for users to input multiple locations. While I have found a way to add input boxes dynamically, I suspect it may not be the most efficient method. As I am new to this, I want to ensure I am doing things correctly. Here is how I curren ...

Exploring innerHTML in JavaScript for event listening

Two code snippets were tested, one worked as expected while the other didn't produce the desired result. The goal was to display a different text every time a user clicked on a button. However, the unsuccessful code always displayed err, with no chang ...

Update the URL and parse the data in a Backbone collection

For the purpose of development, I am looking to replace the collection with fake JSON results either from a JSON variable or a JSON file. However, I encountered an error when attempting to do so using url http://jsfiddle.net/qhoc/uZhM8/ GET http://fiddle ...

How to retrieve FormData data using Axios

One challenge I'm facing is with an application that I have developed using VueJS, where users can upload files and send them to the backend. The process involves using Axios to send the file as FormData. However, once the file is received on the back ...

Trigger an action when the input text is changed, specifically when the input is populated from a different source

Is there a way to trigger an action on an input when the text is changed from another input, like a datepicker? I attempted to trigger the action when I click the date on the datepicker, but it does not seem to be working. Any suggestions? See below for my ...

Error: Cannot access properties that are undefined (specifically '$store')

Login With Vue.js <template> <div class="container mt-5"> <div class="row"> <div class="col-md-12"> <div class="col-md-6"> <div class="form-group&qu ...

Is it possible to programmatically open the Firefox browser console using JavaScript within an extension?

I attempted to link toJavaScriptConsole() with a button, however it is not functioning (undefined reference error) Is there a way to code an XUL button that will launch the firefox browser console, allowing us to view logs from the extension? ...

Make the card change to gray when clicked using Bootstrap

Is it possible to achieve a common function in an infinite list using HTML, CSS, JS, jQuery (on the user's side) where an item will be grayed out after being clicked? How can we implement this effect? 1.) When the user clicks on the card element htt ...

Using Django's template tag in conjunction with Vuetify's input value: a comprehensive guide

Is it possible to combine Django's template tag with Vuetify's input value? I found in Vuetify's documentation that the value can be set using the following method: Click here for more information <template> <v-form> < ...

Strip the CSS styling from an image (the CSS being included in the generated code)

I need to remove the CSS styling from an image, but I can't modify the generated code where it's coming from. My actual code looks like this: <div class="bubble"> <img id="one" src="/static/webupload/MyronArtifacts/images/descarga.png ...